brahe 1.3.4

Brahe is a modern satellite dynamics library for research and engineering applications designed to be easy-to-learn, high-performance, and quick-to-deploy. The north-star of the development is enabling users to solve meaningful problems and answer questions quickly, easily, and correctly.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
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
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
// Access module Python bindings
//
// This file contains Python bindings for the access computation module,
// including constraints, locations, and access window finding.

// ================================
// Properties Dict Wrapper
// ================================

/// A dictionary-like wrapper for Location properties that supports dict-style assignment.
///
/// This class provides a Pythonic dict interface for accessing and modifying location properties.
/// Changes are automatically synchronized with the underlying Location object.
///
/// Example:
///     ```python
///     import brahe as bh
///
///     loc = bh.PointLocation(15.4, 78.2, 0.0)
///
///     # Dict-style assignment
///     loc.properties["climate"] = "Arctic"
///     loc.properties["country"] = "Norway"
///
///     # Dict-style access
///     climate = loc.properties["climate"]
///
///     # Dict methods work
///     if "country" in loc.properties:
///         print(loc.properties["country"])
///
///     # Iteration
///     for key in loc.properties:
///         print(key, loc.properties[key])
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "PropertiesDict")]
pub struct PyPropertiesDict {
    parent: Py<PyAny>,
}

#[pymethods]
impl PyPropertiesDict {
    /// Get a property value by key.
    fn __getitem__(&self, key: String, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_properties_dict(py)?;
        props_dict
            .get_item(&key)?
            .ok_or_else(|| exceptions::PyKeyError::new_err(format!("Key '{}' not found", key)))
            .map(|item| item.unbind())
    }

    /// Set a property value by key.
    ///
    /// Args:
    ///     key (str): Property name
    ///     value (Any): Property value (must be JSON-serializable)
    fn __setitem__(&self, key: String, value: &Bound<'_, PyAny>, py: Python) -> PyResult<()> {
        // Convert Python value to JSON via serialization
        let json_module = py.import("json")?;
        let dumps = json_module.getattr("dumps")?;
        let json_str: String = dumps.call1((value,))?.extract()?;

        let json_value: serde_json::Value = serde_json::from_str(&json_str)
            .map_err(|e| exceptions::PyValueError::new_err(format!("JSON error: {}", e)))?;

        // Update the parent's properties
        self.set_property(py, key, json_value)?;
        Ok(())
    }

    /// Delete a property by key.
    fn __delitem__(&self, key: String, py: Python) -> PyResult<()> {
        self.remove_property(py, key)
    }

    /// Return the number of properties.
    fn __len__(&self, py: Python) -> PyResult<usize> {
        let props_dict = self.get_properties_dict(py)?;
        Ok(props_dict.len())
    }

    /// Check if a key exists in properties.
    fn __contains__(&self, key: String, py: Python) -> PyResult<bool> {
        let props_dict = self.get_properties_dict(py)?;
        props_dict.contains(&key)
    }

    /// Return an iterator over property keys.
    fn __iter__(&self, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_properties_dict(py)?;
        Ok(props_dict.call_method0("__iter__")?.into())
    }

    /// String representation.
    fn __repr__(&self, py: Python) -> PyResult<String> {
        let props_dict = self.get_properties_dict(py)?;
        Ok(format!("PropertiesDict({})", props_dict.repr()?))
    }

    /// Get property value with optional default.
    ///
    /// Args:
    ///     key (str): Property name
    ///     default (optional): Value to return if key not found
    ///
    /// Returns:
    ///     Any: Property value if key exists, otherwise default value
    #[pyo3(signature = (key, default=None))]
    fn get(&self, key: String, default: Option<Py<PyAny>>, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_properties_dict(py)?;
        match props_dict.get_item(&key)? {
            Some(value) => Ok(value.into()),
            None => Ok(default.unwrap_or_else(|| py.None())),
        }
    }

    /// Return a list of property keys.
    ///
    /// Returns:
    ///     List of property key strings
    fn keys(&self, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_properties_dict(py)?;
        Ok(props_dict.call_method0("keys")?.into())
    }

    /// Return a list of property values.
    ///
    /// Returns:
    ///     List of property values
    fn values(&self, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_properties_dict(py)?;
        Ok(props_dict.call_method0("values")?.into())
    }

    /// Return a list of (key, value) tuples.
    ///
    /// Returns:
    ///     List of (key, value) tuples
    fn items(&self, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_properties_dict(py)?;
        Ok(props_dict.call_method0("items")?.into())
    }

    /// Remove all properties.
    ///
    /// Returns:
    ///     None
    fn clear(&self, py: Python) -> PyResult<()> {
        // Get all keys first (to avoid modifying during iteration)
        let props_dict = self.get_properties_dict(py)?;
        let keys_list = props_dict.call_method0("keys")?;
        let keys: Vec<String> = keys_list.extract()?;

        // Remove each key
        for key in keys {
            self.remove_property(py, key)?;
        }
        Ok(())
    }

    /// Update properties from another dict.
    ///
    /// Args:
    ///     other (dict): Dictionary to merge into properties
    ///
    /// Returns:
    ///     None
    fn update(&self, other: &Bound<'_, PyDict>, py: Python) -> PyResult<()> {
        for (key, value) in other.iter() {
            let key_str: String = key.extract()?;
            self.__setitem__(key_str, &value, py)?;
        }
        Ok(())
    }
}

impl PyPropertiesDict {
    /// Create a new PropertiesDict wrapping a parent Location.
    fn new(parent: Py<PyAny>) -> Self {
        Self { parent }
    }

    /// Get the properties as a Python dict.
    fn get_properties_dict<'a>(&self, py: Python<'a>) -> PyResult<Bound<'a, PyDict>> {
        // Call the parent's internal _get_properties_dict method
        let parent_obj = self.parent.bind(py);
        let props_obj = parent_obj.call_method0("_get_properties_dict")?;
        props_obj.cast::<PyDict>().cloned().map_err(|e| e.into())
    }

    /// Set a property on the parent Location.
    fn set_property(&self, py: Python, key: String, value: serde_json::Value) -> PyResult<()> {
        let parent_obj = self.parent.bind(py);
        parent_obj.call_method1("_set_property", (key, value.to_string()))?;
        Ok(())
    }

    /// Remove a property from the parent Location.
    fn remove_property(&self, py: Python, key: String) -> PyResult<()> {
        let parent_obj = self.parent.bind(py);
        parent_obj.call_method1("_remove_property", (key,))?;
        Ok(())
    }
}

// ================================
// Enums
// ================================

/// Look direction of a satellite relative to its velocity vector.
///
/// Indicates whether a satellite is looking to the left (counterclockwise from velocity),
/// right (clockwise from velocity), or either direction.
///
/// This is commonly used for imaging satellites with side-looking sensors or SAR systems
/// that have a preferred look direction.
///
/// Attributes:
///     LEFT: Left-looking (counterclockwise from velocity vector)
///     RIGHT: Right-looking (clockwise from velocity vector)
///     EITHER: Either left or right is acceptable
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Create a constraint for right-looking only satellites
///     constraint = bh.LookDirectionConstraint(allowed=bh.LookDirection.RIGHT)
///
///     # Create a constraint accepting either direction
///     constraint = bh.LookDirectionConstraint(allowed=bh.LookDirection.EITHER)
///
///     # Compare look directions
///     assert bh.LookDirection.LEFT != bh.LookDirection.RIGHT
///     assert bh.LookDirection.LEFT == bh.LookDirection.LEFT
///     ```
#[pyclass(module = "brahe._brahe", from_py_object)]
#[pyo3(name = "LookDirection")]
#[derive(Clone)]
pub struct PyLookDirection {
    pub(crate) value: LookDirection,
}

#[pymethods]
impl PyLookDirection {
    /// Left-looking (counterclockwise from velocity vector)
    #[classattr]
    #[allow(non_snake_case)]
    fn LEFT() -> Self {
        PyLookDirection {
            value: LookDirection::Left,
        }
    }

    /// Right-looking (clockwise from velocity vector)
    #[classattr]
    #[allow(non_snake_case)]
    fn RIGHT() -> Self {
        PyLookDirection {
            value: LookDirection::Right,
        }
    }

    /// Either left or right
    #[classattr]
    #[allow(non_snake_case)]
    fn EITHER() -> Self {
        PyLookDirection {
            value: LookDirection::Either,
        }
    }

    fn __str__(&self) -> String {
        format!("{:?}", self.value)
    }

    fn __repr__(&self) -> String {
        format!("LookDirection.{:?}", self.value)
    }

    fn __richcmp__(&self, other: &Self, op: CompareOp) -> PyResult<bool> {
        match op {
            CompareOp::Eq => Ok(self.value == other.value),
            CompareOp::Ne => Ok(self.value != other.value),
            _ => Err(exceptions::PyNotImplementedError::new_err(
                "Comparison not supported",
            )),
        }
    }
}

/// Ascending or descending pass type for satellite orbits.
///
/// Indicates whether a satellite is moving from south to north (ascending) or
/// north to south (descending) in its orbit. This is determined by the sign of
/// the Z-component of the velocity vector in ECEF coordinates.
///
/// This is useful for:
/// - Sun-synchronous orbits that prefer specific pass types
/// - Minimizing lighting variation between passes
/// - Coordinating multi-satellite observations
///
/// Attributes:
///     ASCENDING: Satellite moving from south to north (vz > 0 in ECEF)
///     DESCENDING: Satellite moving from north to south (vz < 0 in ECEF)
///     EITHER: Either ascending or descending is acceptable
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Create a constraint for ascending passes only
///     constraint = bh.AscDscConstraint(allowed=bh.AscDsc.ASCENDING)
///
///     # Create a constraint for descending passes only
///     constraint = bh.AscDscConstraint(allowed=bh.AscDsc.DESCENDING)
///
///     # Accept either type
///     constraint = bh.AscDscConstraint(allowed=bh.AscDsc.EITHER)
///
///     # Compare pass types
///     assert bh.AscDsc.ASCENDING != bh.AscDsc.DESCENDING
///     assert bh.AscDsc.ASCENDING == bh.AscDsc.ASCENDING
///     ```
#[pyclass(module = "brahe._brahe", from_py_object)]
#[pyo3(name = "AscDsc")]
#[derive(Clone)]
pub struct PyAscDsc {
    pub(crate) value: AscDsc,
}

#[pymethods]
impl PyAscDsc {
    /// Ascending pass (moving from south to north)
    #[classattr]
    #[allow(non_snake_case)]
    fn ASCENDING() -> Self {
        PyAscDsc {
            value: AscDsc::Ascending,
        }
    }

    /// Descending pass (moving from north to south)
    #[classattr]
    #[allow(non_snake_case)]
    fn DESCENDING() -> Self {
        PyAscDsc {
            value: AscDsc::Descending,
        }
    }

    /// Either ascending or descending
    #[classattr]
    #[allow(non_snake_case)]
    fn EITHER() -> Self {
        PyAscDsc {
            value: AscDsc::Either,
        }
    }

    fn __str__(&self) -> String {
        format!("{:?}", self.value)
    }

    fn __repr__(&self) -> String {
        format!("AscDsc.{:?}", self.value)
    }

    fn __richcmp__(&self, other: &Self, op: CompareOp) -> PyResult<bool> {
        match op {
            CompareOp::Eq => Ok(self.value == other.value),
            CompareOp::Ne => Ok(self.value != other.value),
            _ => Err(exceptions::PyNotImplementedError::new_err(
                "Comparison not supported",
            )),
        }
    }
}

// ================================
// Constraint Classes
// ================================

/// Elevation angle constraint for satellite visibility.
///
/// Constrains access based on the elevation angle of the satellite above
/// the local horizon at the ground location.
///
/// Args:
///     min_elevation_deg (float | None): Minimum elevation angle in degrees, or None for no minimum
///     max_elevation_deg (float | None): Maximum elevation angle in degrees, or None for no maximum
///
/// Raises:
///     ValueError: If both min and max are None (unbounded constraint is meaningless)
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Typical ground station constraint: 5° minimum elevation
///     constraint = bh.ElevationConstraint(min_elevation_deg=5.0, max_elevation_deg=None)
///
///     # Both bounds specified
///     constraint = bh.ElevationConstraint(min_elevation_deg=5.0, max_elevation_deg=85.0)
///
///     # Only maximum (e.g., avoid zenith)
///     constraint = bh.ElevationConstraint(min_elevation_deg=None, max_elevation_deg=85.0)
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "ElevationConstraint")]
pub struct PyElevationConstraint {
    pub constraint: ElevationConstraint,
}

#[pymethods]
impl PyElevationConstraint {
    #[new]
    #[pyo3(signature = (min_elevation_deg=None, max_elevation_deg=None))]
    fn new(min_elevation_deg: Option<f64>, max_elevation_deg: Option<f64>) -> PyResult<Self> {
        ElevationConstraint::new(min_elevation_deg, max_elevation_deg)
            .map(|constraint| PyElevationConstraint { constraint })
            .map_err(|e| exceptions::PyValueError::new_err(e.to_string()))
    }

    /// Get the constraint name
    fn name(&self) -> &str {
        self.constraint.name()
    }

    /// Evaluate whether the constraint is satisfied.
    ///
    /// Args:
    ///     epoch (Epoch): Time of evaluation
    ///     sat_state_ecef (ndarray or list): Satellite state in ECEF [x, y, z, vx, vy, vz] (meters, m/s)
    ///     location_ecef (ndarray or list): Ground location in ECEF [x, y, z] (meters)
    ///
    /// Returns:
    ///     bool: True if constraint is satisfied, False otherwise
    fn evaluate(
        &self,
        _py: Python,
        epoch: &PyEpoch,
        sat_state_ecef: &Bound<'_, PyAny>,
        location_ecef: &Bound<'_, PyAny>,
    ) -> PyResult<bool> {
        let sat_state = pyany_to_svector::<6>(sat_state_ecef)?;
        let location = pyany_to_svector::<3>(location_ecef)?;
        Ok(self.constraint.evaluate(&epoch.obj, &sat_state, &location))
    }

    fn __str__(&self) -> String {
        self.constraint.name().to_string()
    }

    fn __repr__(&self) -> String {
        let min_str = match self.constraint.min_elevation_deg {
            Some(v) => format!("Some({})", v),
            None => "None".to_string(),
        };
        let max_str = match self.constraint.max_elevation_deg {
            Some(v) => format!("Some({})", v),
            None => "None".to_string(),
        };
        format!("ElevationConstraint(min_elevation_deg={}, max_elevation_deg={}, name={:?})",
                min_str, max_str, self.constraint.name())
    }
}

/// Azimuth-dependent elevation mask constraint.
///
/// Constrains access based on azimuth-dependent elevation masks.
/// Useful for ground stations with terrain obstructions or antenna limitations.
///
/// The mask is defined as a list of (azimuth, elevation) pairs in degrees.
/// Linear interpolation is used between points, and the mask wraps at 0°/360°.
///
/// Args:
///     mask (list[tuple[float, float]]): List of (azimuth_deg, min_elevation_deg) pairs
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Ground station with terrain obstruction to the north
///     mask = [
///         (0.0, 15.0),     # North: 15° minimum
///         (90.0, 5.0),     # East: 5° minimum
///         (180.0, 5.0),    # South: 5° minimum
///         (270.0, 5.0),    # West: 5° minimum
///     ]
///     constraint = bh.ElevationMaskConstraint(mask)
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "ElevationMaskConstraint")]
pub struct PyElevationMaskConstraint {
    pub constraint: ElevationMaskConstraint,
}

#[pymethods]
impl PyElevationMaskConstraint {
    #[new]
    fn new(mask: Vec<(f64, f64)>) -> Self {
        PyElevationMaskConstraint {
            constraint: ElevationMaskConstraint::new(mask),
        }
    }

    /// Get the constraint name
    fn name(&self) -> &str {
        self.constraint.name()
    }

    /// Evaluate whether the constraint is satisfied.
    ///
    /// Args:
    ///     epoch (Epoch): Time of evaluation
    ///     sat_state_ecef (ndarray or list): Satellite state in ECEF [x, y, z, vx, vy, vz] (meters, m/s)
    ///     location_ecef (ndarray or list): Ground location in ECEF [x, y, z] (meters)
    ///
    /// Returns:
    ///     bool: True if constraint is satisfied, False otherwise
    fn evaluate(
        &self,
        _py: Python,
        epoch: &PyEpoch,
        sat_state_ecef: &Bound<'_, PyAny>,
        location_ecef: &Bound<'_, PyAny>,
    ) -> PyResult<bool> {
        let sat_state = pyany_to_svector::<6>(sat_state_ecef)?;
        let location = pyany_to_svector::<3>(location_ecef)?;
        Ok(self.constraint.evaluate(&epoch.obj, &sat_state, &location))
    }

    fn __str__(&self) -> String {
        self.constraint.name().to_string()
    }

    fn __repr__(&self) -> String {
        format!("ElevationMaskConstraint(mask={:?}, name={:?})",
                self.constraint.mask,
                self.constraint.name())
    }
}

/// Off-nadir angle constraint for satellite imaging.
///
/// Constrains access based on the off-nadir angle (angle between the satellite's
/// nadir vector and the line-of-sight to the location).
///
/// Args:
///     min_off_nadir_deg (float | None): Minimum off-nadir angle in degrees, or None for no minimum
///     max_off_nadir_deg (float | None): Maximum off-nadir angle in degrees, or None for no maximum
///
/// Raises:
///     ValueError: If both min and max are None, or if any angle is negative
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Imaging satellite with 45° maximum slew angle
///     constraint = bh.OffNadirConstraint(min_off_nadir_deg=None, max_off_nadir_deg=45.0)
///
///     # Minimum 10° to avoid nadir (e.g., for oblique imaging)
///     constraint = bh.OffNadirConstraint(min_off_nadir_deg=10.0, max_off_nadir_deg=45.0)
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "OffNadirConstraint")]
pub struct PyOffNadirConstraint {
    pub constraint: OffNadirConstraint,
}

#[pymethods]
impl PyOffNadirConstraint {
    #[new]
    #[pyo3(signature = (min_off_nadir_deg=None, max_off_nadir_deg=None))]
    fn new(min_off_nadir_deg: Option<f64>, max_off_nadir_deg: Option<f64>) -> PyResult<Self> {
        OffNadirConstraint::new(min_off_nadir_deg, max_off_nadir_deg)
            .map(|constraint| PyOffNadirConstraint { constraint })
            .map_err(|e| exceptions::PyValueError::new_err(e.to_string()))
    }

    /// Get the constraint name
    fn name(&self) -> &str {
        self.constraint.name()
    }

    /// Evaluate whether the constraint is satisfied.
    ///
    /// Args:
    ///     epoch (Epoch): Time of evaluation
    ///     sat_state_ecef (ndarray or list): Satellite state in ECEF [x, y, z, vx, vy, vz] (meters, m/s)
    ///     location_ecef (ndarray or list): Ground location in ECEF [x, y, z] (meters)
    ///
    /// Returns:
    ///     bool: True if constraint is satisfied, False otherwise
    fn evaluate(
        &self,
        _py: Python,
        epoch: &PyEpoch,
        sat_state_ecef: &Bound<'_, PyAny>,
        location_ecef: &Bound<'_, PyAny>,
    ) -> PyResult<bool> {
        let sat_state = pyany_to_svector::<6>(sat_state_ecef)?;
        let location = pyany_to_svector::<3>(location_ecef)?;
        Ok(self.constraint.evaluate(&epoch.obj, &sat_state, &location))
    }

    fn __str__(&self) -> String {
        self.constraint.name().to_string()
    }

    fn __repr__(&self) -> String {
        let min_str = match self.constraint.min_off_nadir_deg {
            Some(v) => format!("Some({})", v),
            None => "None".to_string(),
        };
        let max_str = match self.constraint.max_off_nadir_deg {
            Some(v) => format!("Some({})", v),
            None => "None".to_string(),
        };
        format!("OffNadirConstraint(min_off_nadir_deg={}, max_off_nadir_deg={}, name={:?})",
                min_str, max_str, self.constraint.name())
    }
}

/// Local solar time constraint.
///
/// Constrains access based on the local solar time at the ground location.
/// Useful for sun-synchronous orbits or daytime-only imaging.
///
/// Time windows are specified in military time format (HHMM).
/// Wrap-around windows (e.g., 2200-0200) are supported.
///
/// Args:
///     time_windows (list[tuple[int, int]]): List of (start_military, end_military) tuples (0-2400)
///
/// Raises:
///     ValueError: If any military time is invalid (>2400 or minutes >=60)
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Only daytime (6 AM to 6 PM local time)
///     constraint = bh.LocalTimeConstraint(time_windows=[(600, 1800)])
///
///     # Two windows: morning (6-9 AM) and evening (4-7 PM)
///     constraint = bh.LocalTimeConstraint(time_windows=[(600, 900), (1600, 1900)])
///
///     # Overnight window (10 PM to 2 AM) - handles wrap-around
///     constraint = bh.LocalTimeConstraint(time_windows=[(2200, 200)])
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "LocalTimeConstraint")]
pub struct PyLocalTimeConstraint {
    pub constraint: LocalTimeConstraint,
}

#[pymethods]
impl PyLocalTimeConstraint {
    #[new]
    fn new(time_windows: Vec<(u16, u16)>) -> PyResult<Self> {
        LocalTimeConstraint::new(time_windows)
            .map(|constraint| PyLocalTimeConstraint { constraint })
            .map_err(|e| exceptions::PyValueError::new_err(e.to_string()))
    }

    /// Create from decimal hour windows instead of military time.
    ///
    /// Args:
    ///     time_windows (list[tuple[float, float]]): List of (start_hour, end_hour) tuples [0, 24)
    ///
    /// Returns:
    ///     LocalTimeConstraint: The constraint instance
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     # Only daytime (6 AM to 6 PM local time)
    ///     constraint = bh.LocalTimeConstraint.from_hours([(6.0, 18.0)])
    ///
    ///     # Overnight window (10 PM to 2 AM)
    ///     constraint = bh.LocalTimeConstraint.from_hours([(22.0, 2.0)])
    ///     ```
    #[classmethod]
    fn from_hours(_cls: &Bound<'_, PyType>, time_windows: Vec<(f64, f64)>) -> PyResult<Self> {
        LocalTimeConstraint::from_hours(time_windows)
            .map(|constraint| PyLocalTimeConstraint { constraint })
            .map_err(|e| exceptions::PyValueError::new_err(e.to_string()))
    }

    /// Get the constraint name
    fn name(&self) -> &str {
        self.constraint.name()
    }

    /// Evaluate whether the constraint is satisfied.
    ///
    /// Args:
    ///     epoch (Epoch): Time of evaluation
    ///     sat_state_ecef (ndarray or list): Satellite state in ECEF [x, y, z, vx, vy, vz] (meters, m/s)
    ///     location_ecef (ndarray or list): Ground location in ECEF [x, y, z] (meters)
    ///
    /// Returns:
    ///     bool: True if constraint is satisfied, False otherwise
    fn evaluate(
        &self,
        _py: Python,
        epoch: &PyEpoch,
        sat_state_ecef: &Bound<'_, PyAny>,
        location_ecef: &Bound<'_, PyAny>,
    ) -> PyResult<bool> {
        let sat_state = pyany_to_svector::<6>(sat_state_ecef)?;
        let location = pyany_to_svector::<3>(location_ecef)?;
        Ok(self.constraint.evaluate(&epoch.obj, &sat_state, &location))
    }

    fn __str__(&self) -> String {
        self.constraint.name().to_string()
    }

    fn __repr__(&self) -> String {
        format!("LocalTimeConstraint(time_windows={:?}, name={:?})",
                self.constraint.time_windows,
                self.constraint.name())
    }
}

/// Look direction constraint (left/right relative to velocity).
///
/// Constrains access based on the look direction of the satellite relative
/// to its velocity vector.
///
/// Args:
///     allowed (LookDirection): Required look direction (LEFT, RIGHT, or EITHER)
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Satellite can only look right
///     constraint = bh.LookDirectionConstraint(allowed=bh.LookDirection.RIGHT)
///
///     # Either direction is acceptable
///     constraint = bh.LookDirectionConstraint(allowed=bh.LookDirection.EITHER)
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "LookDirectionConstraint")]
pub struct PyLookDirectionConstraint {
    pub constraint: LookDirectionConstraint,
}

#[pymethods]
impl PyLookDirectionConstraint {
    #[new]
    fn new(allowed: &PyLookDirection) -> Self {
        PyLookDirectionConstraint {
            constraint: LookDirectionConstraint::new(allowed.value),
        }
    }

    /// Get the constraint name
    fn name(&self) -> &str {
        self.constraint.name()
    }

    /// Evaluate whether the constraint is satisfied.
    ///
    /// Args:
    ///     epoch (Epoch): Time of evaluation
    ///     sat_state_ecef (ndarray or list): Satellite state in ECEF [x, y, z, vx, vy, vz] (meters, m/s)
    ///     location_ecef (ndarray or list): Ground location in ECEF [x, y, z] (meters)
    ///
    /// Returns:
    ///     bool: True if constraint is satisfied, False otherwise
    fn evaluate(
        &self,
        _py: Python,
        epoch: &PyEpoch,
        sat_state_ecef: &Bound<'_, PyAny>,
        location_ecef: &Bound<'_, PyAny>,
    ) -> PyResult<bool> {
        let sat_state = pyany_to_svector::<6>(sat_state_ecef)?;
        let location = pyany_to_svector::<3>(location_ecef)?;
        Ok(self.constraint.evaluate(&epoch.obj, &sat_state, &location))
    }

    fn __str__(&self) -> String {
        self.constraint.name().to_string()
    }

    fn __repr__(&self) -> String {
        format!("LookDirectionConstraint(allowed={:?}, name={:?})",
                self.constraint.allowed,
                self.constraint.name())
    }
}

/// Ascending/descending pass constraint.
///
/// Constrains access based on whether the satellite is on an ascending or
/// descending pass (moving north or south).
///
/// Args:
///     allowed (AscDsc): Required pass type (ASCENDING, DESCENDING, or EITHER)
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Only ascending passes
///     constraint = bh.AscDscConstraint(allowed=bh.AscDsc.ASCENDING)
///
///     # Either type is acceptable
///     constraint = bh.AscDscConstraint(allowed=bh.AscDsc.EITHER)
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "AscDscConstraint")]
pub struct PyAscDscConstraint {
    pub constraint: AscDscConstraint,
}

#[pymethods]
impl PyAscDscConstraint {
    #[new]
    fn new(allowed: &PyAscDsc) -> Self {
        PyAscDscConstraint {
            constraint: AscDscConstraint::new(allowed.value),
        }
    }

    /// Get the constraint name
    fn name(&self) -> &str {
        self.constraint.name()
    }

    /// Evaluate whether the constraint is satisfied.
    ///
    /// Args:
    ///     epoch (Epoch): Time of evaluation
    ///     sat_state_ecef (ndarray or list): Satellite state in ECEF [x, y, z, vx, vy, vz] (meters, m/s)
    ///     location_ecef (ndarray or list): Ground location in ECEF [x, y, z] (meters)
    ///
    /// Returns:
    ///     bool: True if constraint is satisfied, False otherwise
    fn evaluate(
        &self,
        _py: Python,
        epoch: &PyEpoch,
        sat_state_ecef: &Bound<'_, PyAny>,
        location_ecef: &Bound<'_, PyAny>,
    ) -> PyResult<bool> {
        let sat_state = pyany_to_svector::<6>(sat_state_ecef)?;
        let location = pyany_to_svector::<3>(location_ecef)?;
        Ok(self.constraint.evaluate(&epoch.obj, &sat_state, &location))
    }

    fn __str__(&self) -> String {
        self.constraint.name().to_string()
    }

    fn __repr__(&self) -> String {
        format!("AscDscConstraint(allowed={:?}, name={:?})",
                self.constraint.allowed,
                self.constraint.name())
    }
}

// ================================
// Constraint Composition
// ================================

/// Composite constraint combining multiple constraints with AND logic.
///
/// All constraints must be satisfied for the composite to evaluate to true.
///
/// Args:
///     constraints (Sequence): List of constraint objects to combine with AND logic
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Ground station with multiple requirements
///     elev = bh.ElevationConstraint(min_elevation_deg=5.0, max_elevation_deg=None)
///     time = bh.LocalTimeConstraint(time_windows=[(600, 1800)])
///     combined = bh.ConstraintAll(constraints=[elev, time])
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "ConstraintAll")]
pub struct PyConstraintAll {
    pub composite: ConstraintComposite,
}

#[pymethods]
impl PyConstraintAll {
    #[new]
    fn new(constraints: Vec<Py<PyAny>>) -> PyResult<Self> {
        // Convert Python objects to Rust constraint trait objects
        // For now, we'll store them as-is and handle evaluation in Rust
        // This requires implementing conversion logic for each constraint type

        // Note: This is a simplified version. Full implementation would need
        // to check the type of each Py<PyAny> and convert to the appropriate
        // Rust constraint type
        Python::attach(|py| {
            let mut rust_constraints: Vec<Box<dyn AccessConstraint>> = Vec::new();

            for py_obj in constraints {
                // Try to extract each constraint type
                if let Ok(c) = py_obj.extract::<PyRef<PyElevationConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else if let Ok(c) = py_obj.extract::<PyRef<PyElevationMaskConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else if let Ok(c) = py_obj.extract::<PyRef<PyOffNadirConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else if let Ok(c) = py_obj.extract::<PyRef<PyLocalTimeConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else if let Ok(c) = py_obj.extract::<PyRef<PyLookDirectionConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else if let Ok(c) = py_obj.extract::<PyRef<PyAscDscConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else {
                    return Err(exceptions::PyTypeError::new_err(
                        "All constraints must be valid constraint objects"
                    ));
                }
            }

            Ok(PyConstraintAll {
                composite: ConstraintComposite::All(rust_constraints),
            })
        })
    }

    /// Get the constraint name
    fn name(&self) -> &str {
        self.composite.name()
    }

    /// Evaluate whether the constraint is satisfied.
    ///
    /// Args:
    ///     epoch (Epoch): Time of evaluation
    ///     sat_state_ecef (ndarray or list): Satellite state in ECEF [x, y, z, vx, vy, vz] (meters, m/s)
    ///     location_ecef (ndarray or list): Ground location in ECEF [x, y, z] (meters)
    ///
    /// Returns:
    ///     bool: True if ALL constraints are satisfied, False otherwise
    fn evaluate(
        &self,
        _py: Python,
        epoch: &PyEpoch,
        sat_state_ecef: &Bound<'_, PyAny>,
        location_ecef: &Bound<'_, PyAny>,
    ) -> PyResult<bool> {
        let sat_state = pyany_to_svector::<6>(sat_state_ecef)?;
        let location = pyany_to_svector::<3>(location_ecef)?;
        Ok(self.composite.evaluate(&epoch.obj, &sat_state, &location))
    }

    fn __str__(&self) -> String {
        self.composite.format_string()
    }

    fn __repr__(&self) -> String {
        format!("{:?}", self.composite)
    }
}

/// Composite constraint combining multiple constraints with OR logic.
///
/// At least one constraint must be satisfied for the composite to evaluate to true.
///
/// Args:
///     constraints (Sequence): List of constraint objects to combine with OR logic
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Accept either high elevation or specific time window
///     elev = bh.ElevationConstraint(min_elevation_deg=60.0, max_elevation_deg=None)
///     time = bh.LocalTimeConstraint(time_windows=[(1200, 1400)])
///     combined = bh.ConstraintAny(constraints=[elev, time])
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "ConstraintAny")]
pub struct PyConstraintAny {
    pub composite: ConstraintComposite,
}

#[pymethods]
impl PyConstraintAny {
    #[new]
    fn new(constraints: Vec<Py<PyAny>>) -> PyResult<Self> {
        Python::attach(|py| {
            let mut rust_constraints: Vec<Box<dyn AccessConstraint>> = Vec::new();

            for py_obj in constraints {
                if let Ok(c) = py_obj.extract::<PyRef<PyElevationConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else if let Ok(c) = py_obj.extract::<PyRef<PyElevationMaskConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else if let Ok(c) = py_obj.extract::<PyRef<PyOffNadirConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else if let Ok(c) = py_obj.extract::<PyRef<PyLocalTimeConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else if let Ok(c) = py_obj.extract::<PyRef<PyLookDirectionConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else if let Ok(c) = py_obj.extract::<PyRef<PyAscDscConstraint>>(py) {
                    rust_constraints.push(Box::new(c.constraint.clone()));
                } else {
                    return Err(exceptions::PyTypeError::new_err(
                        "All constraints must be valid constraint objects"
                    ));
                }
            }

            Ok(PyConstraintAny {
                composite: ConstraintComposite::Any(rust_constraints),
            })
        })
    }

    /// Get the constraint name
    fn name(&self) -> &str {
        self.composite.name()
    }

    /// Evaluate whether the constraint is satisfied.
    ///
    /// Args:
    ///     epoch (Epoch): Time of evaluation
    ///     sat_state_ecef (ndarray or list): Satellite state in ECEF [x, y, z, vx, vy, vz] (meters, m/s)
    ///     location_ecef (ndarray or list): Ground location in ECEF [x, y, z] (meters)
    ///
    /// Returns:
    ///     bool: True if AT LEAST ONE constraint is satisfied, False otherwise
    fn evaluate(
        &self,
        _py: Python,
        epoch: &PyEpoch,
        sat_state_ecef: &Bound<'_, PyAny>,
        location_ecef: &Bound<'_, PyAny>,
    ) -> PyResult<bool> {
        let sat_state = pyany_to_svector::<6>(sat_state_ecef)?;
        let location = pyany_to_svector::<3>(location_ecef)?;
        Ok(self.composite.evaluate(&epoch.obj, &sat_state, &location))
    }

    fn __str__(&self) -> String {
        self.composite.format_string()
    }

    fn __repr__(&self) -> String {
        format!("{:?}", self.composite)
    }
}

/// Composite constraint negating another constraint with NOT logic.
///
/// The negated constraint must NOT be satisfied for this to evaluate to true.
///
/// Args:
///     constraint (object): Constraint object to negate
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Avoid low elevation angles (i.e., require high elevation)
///     low_elev = bh.ElevationConstraint(min_elevation_deg=None, max_elevation_deg=10.0)
///     high_elev = bh.ConstraintNot(constraint=low_elev)
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "ConstraintNot")]
pub struct PyConstraintNot {
    pub composite: ConstraintComposite,
}

#[pymethods]
impl PyConstraintNot {
    #[new]
    fn new(constraint: Py<PyAny>) -> PyResult<Self> {
        Python::attach(|py| {
            let rust_constraint: Box<dyn AccessConstraint> =
                if let Ok(c) = constraint.extract::<PyRef<PyElevationConstraint>>(py) {
                    Box::new(c.constraint.clone())
                } else if let Ok(c) = constraint.extract::<PyRef<PyElevationMaskConstraint>>(py) {
                    Box::new(c.constraint.clone())
                } else if let Ok(c) = constraint.extract::<PyRef<PyOffNadirConstraint>>(py) {
                    Box::new(c.constraint.clone())
                } else if let Ok(c) = constraint.extract::<PyRef<PyLocalTimeConstraint>>(py) {
                    Box::new(c.constraint.clone())
                } else if let Ok(c) = constraint.extract::<PyRef<PyLookDirectionConstraint>>(py) {
                    Box::new(c.constraint.clone())
                } else if let Ok(c) = constraint.extract::<PyRef<PyAscDscConstraint>>(py) {
                    Box::new(c.constraint.clone())
                } else {
                    return Err(exceptions::PyTypeError::new_err(
                        "Constraint must be a valid constraint object"
                    ));
                };

            Ok(PyConstraintNot {
                composite: ConstraintComposite::Not(rust_constraint),
            })
        })
    }

    /// Get the constraint name
    fn name(&self) -> &str {
        self.composite.name()
    }

    /// Evaluate whether the constraint is satisfied.
    ///
    /// Args:
    ///     epoch (Epoch): Time of evaluation
    ///     sat_state_ecef (ndarray or list): Satellite state in ECEF [x, y, z, vx, vy, vz] (meters, m/s)
    ///     location_ecef (ndarray or list): Ground location in ECEF [x, y, z] (meters)
    ///
    /// Returns:
    ///     bool: True if the negated constraint is NOT satisfied, False otherwise
    fn evaluate(
        &self,
        _py: Python,
        epoch: &PyEpoch,
        sat_state_ecef: &Bound<'_, PyAny>,
        location_ecef: &Bound<'_, PyAny>,
    ) -> PyResult<bool> {
        let sat_state = pyany_to_svector::<6>(sat_state_ecef)?;
        let location = pyany_to_svector::<3>(location_ecef)?;
        Ok(self.composite.evaluate(&epoch.obj, &sat_state, &location))
    }

    fn __str__(&self) -> String {
        self.composite.format_string()
    }

    fn __repr__(&self) -> String {
        format!("{:?}", self.composite)
    }
}

// ================================
// Location Classes
// ================================

/// A single point location on Earth's surface.
///
/// Represents a discrete point with geodetic coordinates (longitude, latitude, altitude).
/// Commonly used for ground stations, imaging targets, or tessellated polygon tiles.
///
/// Args:
///     lon (float): Longitude in degrees (-180 to 180)
///     lat (float): Latitude in degrees (-90 to 90)
///     alt (float): Altitude above ellipsoid in meters (default: 0.0)
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Create a ground station in Svalbard
///     svalbard = bh.PointLocation(lon=15.4, lat=78.2, alt=0.0)
///
///     # With identity
///     svalbard = bh.PointLocation(lon=15.4, lat=78.2, alt=0.0) \\
///         .with_name("Svalbard Ground Station") \\
///         .with_id(1)
///
///     # With custom properties
///     svalbard = bh.PointLocation(lon=15.4, lat=78.2, alt=0.0) \\
///         .add_property("country", "Norway") \\
///         .add_property("min_elevation_deg", 5.0)
///
///     # Access coordinates as properties
///     lon = svalbard.lon  # Property (always degrees)
///     lat = svalbard.lat  # Property (always degrees)
///     lat_rad = svalbard.latitude(bh.AngleFormat.RADIANS)  # Method for format conversion
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "PointLocation")]
pub struct PyPointLocation {
    pub location: PointLocation,
}

#[pymethods]
impl PyPointLocation {
    #[new]
    #[pyo3(signature = (lon, lat, alt=0.0))]
    fn new(lon: f64, lat: f64, alt: f64) -> Self {
        PyPointLocation {
            location: PointLocation::new(lon, lat, alt),
        }
    }

    /// Create from GeoJSON Point Feature.
    ///
    /// Args:
    ///     geojson (dict): GeoJSON Feature object with Point geometry
    ///
    /// Returns:
    ///     PointLocation: New location instance
    ///
    /// Raises:
    ///     ValueError: If GeoJSON is invalid or not a Point Feature
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     geojson = {
    ///         "type": "Feature",
    ///         "geometry": {
    ///             "type": "Point",
    ///             "coordinates": [15.4, 78.2, 0.0]
    ///         },
    ///         "properties": {
    ///             "name": "Svalbard"
    ///         }
    ///     }
    ///
    ///     location = bh.PointLocation.from_geojson(geojson)
    ///     ```
    #[classmethod]
    fn from_geojson(_cls: &Bound<'_, PyType>, geojson: &Bound<'_, PyAny>) -> PyResult<Self> {
        // Convert Python dict to serde_json::Value
        let json_str = Python::attach(|py| -> PyResult<String> {
            let json_module = py.import("json")?;
            let dumps = json_module.getattr("dumps")?;
            let json_str = dumps.call1((geojson,))?;
            json_str.extract()
        })?;

        let json_value: serde_json::Value = serde_json::from_str(&json_str)
            .map_err(|e| exceptions::PyValueError::new_err(format!("Invalid JSON: {}", e)))?;

        PointLocation::from_geojson(&json_value)
            .map(|location| PyPointLocation { location })
            .map_err(|e| exceptions::PyValueError::new_err(e.to_string()))
    }

    /// Get longitude in degrees.
    ///
    /// Returns:
    ///     float: Longitude in degrees
    #[getter]
    fn lon(&self) -> f64 {
        self.location.lon()
    }

    /// Get latitude in degrees.
    ///
    /// Returns:
    ///     float: Latitude in degrees
    #[getter]
    fn lat(&self) -> f64 {
        self.location.lat()
    }

    /// Get altitude in meters.
    ///
    /// Returns:
    ///     float: Altitude in meters
    #[getter]
    fn alt(&self) -> f64 {
        self.location.alt()
    }

    /// Get longitude with angle format conversion.
    ///
    /// Args:
    ///     angle_format (AngleFormat): Desired output format (DEGREES or RADIANS)
    ///
    /// Returns:
    ///     float: Longitude in specified format
    fn longitude(&self, angle_format: &PyAngleFormat) -> f64 {
        self.location.longitude(angle_format.value)
    }

    /// Get latitude with angle format conversion.
    ///
    /// Args:
    ///     angle_format (AngleFormat): Desired output format (DEGREES or RADIANS)
    ///
    /// Returns:
    ///     float: Latitude in specified format
    fn latitude(&self, angle_format: &PyAngleFormat) -> f64 {
        self.location.latitude(angle_format.value)
    }

    /// Get altitude in meters.
    ///
    /// Returns:
    ///     float: Altitude in meters
    fn altitude(&self) -> f64 {
        self.location.altitude()
    }

    /// Get center coordinates in geodetic format [lon, lat, alt].
    ///
    /// Returns:
    ///     ndarray: Geodetic coordinates [longitude_deg, latitude_deg, altitude_m]
    fn center_geodetic(&self, py: Python) -> Py<PyAny> {
        let center = self.location.center_geodetic();
        vec![center.x, center.y, center.z].into_pyarray(py).into_any().unbind()
    }

    /// Get center position in ECEF coordinates [x, y, z].
    ///
    /// Returns:
    ///     ndarray: ECEF position in meters [x, y, z]
    fn center_ecef(&self, py: Python) -> Py<PyAny> {
        let ecef = self.location.center_ecef();
        vec![ecef.x, ecef.y, ecef.z].into_pyarray(py).into_any().unbind()
    }

    /// Get custom properties dictionary.
    ///
    /// Returns:
    ///     PropertiesDict: Dictionary-like wrapper for properties that supports assignment
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     loc = bh.PointLocation(15.4, 78.2, 0.0)
    ///
    ///     # Dict-style assignment
    ///     loc.properties["climate"] = "Arctic"
    ///     loc.properties["country"] = "Norway"
    ///
    ///     # Dict-style access
    ///     print(loc.properties["climate"])  # "Arctic"
    ///
    ///     # Dict methods
    ///     if "country" in loc.properties:
    ///         del loc.properties["country"]
    ///
    ///     # Iteration
    ///     for key in loc.properties.keys():
    ///         print(key, loc.properties[key])
    ///     ```
    #[getter]
    fn properties(slf: Bound<'_, Self>) -> PyResult<Py<PyPropertiesDict>> {
        let py = slf.py();
        let parent: Py<PyAny> = slf.clone().into_any().unbind();
        Py::new(py, PyPropertiesDict::new(parent))
    }

    /// Internal method: Get properties as a plain Python dict.
    #[pyo3(name = "_get_properties_dict")]
    fn get_properties_dict(&self, py: Python) -> PyResult<Py<PyAny>> {
        let props = self.location.properties();
        let py_dict = PyDict::new(py);

        for (key, value) in props.iter() {
            let py_value = serde_json::to_string(value)
                .map_err(|e| exceptions::PyValueError::new_err(format!("JSON error: {}", e)))?;
            let json_module = py.import("json")?;
            let loads = json_module.getattr("loads")?;
            let py_val = loads.call1((py_value,))?;
            py_dict.set_item(key, py_val)?;
        }

        Ok(py_dict.into())
    }

    /// Internal method: Set a property value.
    #[pyo3(name = "_set_property")]
    fn set_property(&mut self, key: String, json_str: String) -> PyResult<()> {
        let value: serde_json::Value = serde_json::from_str(&json_str)
            .map_err(|e| exceptions::PyValueError::new_err(format!("JSON error: {}", e)))?;
        self.location.properties_mut().insert(key, value);
        Ok(())
    }

    /// Internal method: Remove a property.
    #[pyo3(name = "_remove_property")]
    fn remove_property(&mut self, key: String) -> PyResult<()> {
        self.location.properties_mut().remove(&key)
            .ok_or_else(|| exceptions::PyKeyError::new_err(format!("Key '{}' not found", key)))?;
        Ok(())
    }

    /// Export to GeoJSON Feature format.
    ///
    /// Returns:
    ///     dict: GeoJSON Feature object
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     location = bh.PointLocation(lon=15.4, lat=78.2, alt=0.0) \\
    ///         .with_name("Svalbard")
    ///
    ///     geojson = location.to_geojson()
    ///     # Returns:
    ///     # {
    ///     #     "type": "Feature",
    ///     #     "geometry": {
    ///     #         "type": "Point",
    ///     #         "coordinates": [15.4, 78.2, 0.0]
    ///     #     },
    ///     #     "properties": {
    ///     #         "name": "Svalbard"
    ///     #     }
    ///     # }
    ///     ```
    fn to_geojson(&self, py: Python) -> PyResult<Py<PyAny>> {
        let geojson = self.location.to_geojson();
        let json_str = serde_json::to_string(&geojson)
            .map_err(|e| exceptions::PyValueError::new_err(format!("JSON error: {}", e)))?;

        let json_module = py.import("json")?;
        let loads = json_module.getattr("loads")?;
        let result = loads.call1((json_str,))?;
        Ok(result.into())
    }

    /// Add a custom property (builder pattern).
    ///
    /// Args:
    ///     key (str): Property name
    ///     value (Any): Property value (must be JSON-serializable)
    ///
    /// Returns:
    ///     PointLocation: Self for chaining
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     location = bh.PointLocation(lon=15.4, lat=78.2, alt=0.0) \\
    ///         .add_property("country", "Norway") \\
    ///         .add_property("elevation_mask_deg", 5.0)
    ///     ```
    fn add_property<'py>(mut slf: PyRefMut<'py, Self>, key: String, value: &Bound<'py, PyAny>) -> PyResult<PyRefMut<'py, Self>> {
        // Convert Python value to serde_json::Value
        let json_str = Python::attach(|py| -> PyResult<String> {
            let json_module = py.import("json")?;
            let dumps = json_module.getattr("dumps")?;
            let json_str = dumps.call1((value,))?;
            json_str.extract()
        })?;

        let json_value: serde_json::Value = serde_json::from_str(&json_str)
            .map_err(|e| exceptions::PyValueError::new_err(format!("Invalid JSON: {}", e)))?;

        slf.location = slf.location.clone().add_property(&key, json_value);
        Ok(slf)
    }

    // ===== Identifiable trait methods =====

    /// Set the name (builder pattern).
    ///
    /// Args:
    ///     name (str): Human-readable name
    ///
    /// Returns:
    ///     PointLocation: Self for chaining
    fn with_name(mut slf: PyRefMut<'_, Self>, name: String) -> PyRefMut<'_, Self> {
        slf.location = slf.location.clone().with_name(&name);
        slf
    }

    /// Set the numeric ID (builder pattern).
    ///
    /// Args:
    ///     id (int): Numeric identifier
    ///
    /// Returns:
    ///     PointLocation: Self for chaining
    fn with_id(mut slf: PyRefMut<'_, Self>, id: u64) -> PyRefMut<'_, Self> {
        slf.location = slf.location.clone().with_id(id);
        slf
    }

    /// Set the UUID from a string (builder pattern).
    ///
    /// Args:
    ///     uuid_str (str): UUID string
    ///
    /// Returns:
    ///     PointLocation: Self for chaining
    ///
    /// Raises:
    ///     ValueError: If UUID string is invalid
    fn with_uuid(mut slf: PyRefMut<'_, Self>, uuid_str: String) -> PyResult<PyRefMut<'_, Self>> {
        let uuid = uuid::Uuid::parse_str(&uuid_str)
            .map_err(|e| exceptions::PyValueError::new_err(format!("Invalid UUID: {}", e)))?;
        slf.location = slf.location.clone().with_uuid(uuid);
        Ok(slf)
    }

    /// Generate a new UUID (builder pattern).
    ///
    /// Returns:
    ///     PointLocation: Self for chaining
    fn with_new_uuid(mut slf: PyRefMut<'_, Self>) -> PyRefMut<'_, Self> {
        slf.location = slf.location.clone().with_new_uuid();
        slf
    }

    /// Get the name.
    ///
    /// Returns:
    ///     str | None: Name if set, None otherwise
    fn get_name(&self) -> Option<String> {
        self.location.get_name().map(|s| s.to_string())
    }

    /// Get the numeric ID.
    ///
    /// Returns:
    ///     int | None: ID if set, None otherwise
    fn get_id(&self) -> Option<u64> {
        self.location.get_id()
    }

    /// Get the UUID as a string.
    ///
    /// Returns:
    ///     str | None: UUID string if set, None otherwise
    fn get_uuid(&self) -> Option<String> {
        self.location.get_uuid().map(|u| u.to_string())
    }

    /// Set the name (mutating).
    ///
    /// Args:
    ///     name (str | None): Name to set, or None to clear
    fn set_name(&mut self, name: Option<String>) {
        self.location.set_name(name.as_deref());
    }

    /// Set the numeric ID (mutating).
    ///
    /// Args:
    ///     id (int | None): ID to set, or None to clear
    fn set_id(&mut self, id: Option<u64>) {
        self.location.set_id(id);
    }

    /// Generate a new UUID (mutating).
    fn generate_uuid(&mut self) {
        self.location.generate_uuid();
    }

    fn __str__(&self) -> String {
        if let Some(name) = self.location.get_name() {
            format!("PointLocation({}, lon={:.4}°, lat={:.4}°, alt={:.1}m)",
                name, self.location.lon(), self.location.lat(), self.location.alt())
        } else {
            format!("PointLocation(lon={:.4}°, lat={:.4}°, alt={:.1}m)",
                self.location.lon(), self.location.lat(), self.location.alt())
        }
    }

    fn __repr__(&self) -> String {
        self.__str__()
    }
}

/// A polygonal area on Earth's surface.
///
/// Represents a closed polygon with multiple vertices.
/// Commonly used for areas of interest, no-fly zones, or imaging footprints.
///
/// The polygon is automatically closed if the first and last vertices don't match.
///
/// Args:
///     vertices (list[list[float]]): List of [lon, lat, alt] vertices in degrees and meters
///
/// Raises:
///     ValueError: If polygon has fewer than 4 vertices or has validation errors
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Define a rectangular area
///     vertices = [
///         [10.0, 50.0, 0.0],  # lon, lat, alt
///         [11.0, 50.0, 0.0],
///         [11.0, 51.0, 0.0],
///         [10.0, 51.0, 0.0],
///         [10.0, 50.0, 0.0],  # Closed (first == last)
///     ]
///     polygon = bh.PolygonLocation(vertices)
///
///     # With identity
///     polygon = bh.PolygonLocation(vertices) \\
///         .with_name("AOI-1") \\
///         .add_property("region", "Europe")
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "PolygonLocation")]
pub struct PyPolygonLocation {
    pub location: PolygonLocation,
}

#[pymethods]
impl PyPolygonLocation {
    #[new]
    fn new(vertices: Vec<Vec<f64>>) -> PyResult<Self> {
        // Convert Vec<Vec<f64>> to Vec<Vector3<f64>>
        let mut vec3_vertices = Vec::new();
        for vertex in vertices {
            if vertex.len() != 3 {
                return Err(exceptions::PyValueError::new_err(
                    "Each vertex must have [lon, lat, alt]",
                ));
            }
            vec3_vertices.push(Vector3::new(vertex[0], vertex[1], vertex[2]));
        }

        PolygonLocation::new(vec3_vertices)
            .map(|location| PyPolygonLocation { location })
            .map_err(|e| exceptions::PyValueError::new_err(e.to_string()))
    }

    /// Create from GeoJSON Polygon Feature.
    ///
    /// Args:
    ///     geojson (dict): GeoJSON Feature object with Polygon geometry
    ///
    /// Returns:
    ///     PolygonLocation: New polygon instance
    ///
    /// Raises:
    ///     ValueError: If GeoJSON is invalid or not a Polygon Feature
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     geojson = {
    ///         "type": "Feature",
    ///         "geometry": {
    ///             "type": "Polygon",
    ///             "coordinates": [[
    ///                 [10.0, 50.0, 0.0],
    ///                 [11.0, 50.0, 0.0],
    ///                 [11.0, 51.0, 0.0],
    ///                 [10.0, 51.0, 0.0],
    ///                 [10.0, 50.0, 0.0]
    ///             ]]
    ///         },
    ///         "properties": {
    ///             "name": "AOI-1"
    ///         }
    ///     }
    ///
    ///     polygon = bh.PolygonLocation.from_geojson(geojson)
    ///     ```
    #[classmethod]
    fn from_geojson(_cls: &Bound<'_, PyType>, geojson: &Bound<'_, PyAny>) -> PyResult<Self> {
        // Convert Python dict to serde_json::Value
        let json_str = Python::attach(|py| -> PyResult<String> {
            let json_module = py.import("json")?;
            let dumps = json_module.getattr("dumps")?;
            let json_str = dumps.call1((geojson,))?;
            json_str.extract()
        })?;

        let json_value: serde_json::Value = serde_json::from_str(&json_str)
            .map_err(|e| exceptions::PyValueError::new_err(format!("Invalid JSON: {}", e)))?;

        PolygonLocation::from_geojson(&json_value)
            .map(|location| PyPolygonLocation { location })
            .map_err(|e| exceptions::PyValueError::new_err(e.to_string()))
    }

    /// Get polygon vertices.
    ///
    /// Returns all vertices including the closure vertex (first == last).
    ///
    /// Returns:
    ///     ndarray: Vertices as Nx3 array [[lon, lat, alt], ...]
    #[getter]
    fn vertices(&self, py: Python) -> Py<PyAny> {
        let verts = self.location.vertices();
        let n = verts.len();
        let mut data = Vec::new();
        for v in verts {
            data.extend_from_slice(&[v.x, v.y, v.z]);
        }
        data.into_pyarray(py).reshape([n, 3]).unwrap().into_any().unbind()
    }

    /// Get number of unique vertices (excluding closure).
    ///
    /// Returns:
    ///     int: Number of unique vertices
    #[getter]
    fn num_vertices(&self) -> usize {
        self.location.num_vertices()
    }

    /// Get center longitude in degrees.
    ///
    /// Returns:
    ///     float: Center longitude in degrees
    #[getter]
    fn lon(&self) -> f64 {
        self.location.lon()
    }

    /// Get center latitude in degrees.
    ///
    /// Returns:
    ///     float: Center latitude in degrees
    #[getter]
    fn lat(&self) -> f64 {
        self.location.lat()
    }

    /// Get center altitude in meters.
    ///
    /// Returns:
    ///     float: Center altitude in meters
    #[getter]
    fn alt(&self) -> f64 {
        self.location.alt()
    }

    /// Get center longitude with angle format conversion.
    ///
    /// Args:
    ///     angle_format (AngleFormat): Desired output format (DEGREES or RADIANS)
    ///
    /// Returns:
    ///     float: Center longitude in specified format
    fn longitude(&self, angle_format: &PyAngleFormat) -> f64 {
        self.location.longitude(angle_format.value)
    }

    /// Get center latitude with angle format conversion.
    ///
    /// Args:
    ///     angle_format (AngleFormat): Desired output format (DEGREES or RADIANS)
    ///
    /// Returns:
    ///     float: Center latitude in specified format
    fn latitude(&self, angle_format: &PyAngleFormat) -> f64 {
        self.location.latitude(angle_format.value)
    }

    /// Get center altitude in meters.
    ///
    /// Returns:
    ///     float: Center altitude in meters
    fn altitude(&self) -> f64 {
        self.location.altitude()
    }

    /// Get center coordinates in geodetic format [lon, lat, alt].
    ///
    /// Returns:
    ///     ndarray: Geodetic coordinates [longitude_deg, latitude_deg, altitude_m]
    fn center_geodetic(&self, py: Python) -> Py<PyAny> {
        let center = self.location.center_geodetic();
        vec![center.x, center.y, center.z].into_pyarray(py).into_any().unbind()
    }

    /// Get center position in ECEF coordinates [x, y, z].
    ///
    /// Returns:
    ///     ndarray: ECEF position in meters [x, y, z]
    fn center_ecef(&self, py: Python) -> Py<PyAny> {
        let ecef = self.location.center_ecef();
        vec![ecef.x, ecef.y, ecef.z].into_pyarray(py).into_any().unbind()
    }

    /// Get custom properties dictionary.
    ///
    /// Returns:
    ///     PropertiesDict: Dictionary-like wrapper for properties that supports assignment
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     verts = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]]
    ///     poly = bh.PolygonLocation(verts)
    ///
    ///     # Dict-style assignment
    ///     poly.properties["region"] = "Test Area"
    ///     poly.properties["area_km2"] = 123.45
    ///
    ///     # Dict-style access
    ///     print(poly.properties["region"])  # "Test Area"
    ///
    ///     # Dict methods
    ///     if "area_km2" in poly.properties:
    ///         del poly.properties["area_km2"]
    ///     ```
    #[getter]
    fn properties(slf: Bound<'_, Self>) -> PyResult<Py<PyPropertiesDict>> {
        let py = slf.py();
        let parent: Py<PyAny> = slf.clone().into_any().unbind();
        Py::new(py, PyPropertiesDict::new(parent))
    }

    /// Internal method: Get properties as a plain Python dict.
    #[pyo3(name = "_get_properties_dict")]
    fn get_properties_dict(&self, py: Python) -> PyResult<Py<PyAny>> {
        let props = self.location.properties();
        let py_dict = PyDict::new(py);

        for (key, value) in props.iter() {
            let py_value = serde_json::to_string(value)
                .map_err(|e| exceptions::PyValueError::new_err(format!("JSON error: {}", e)))?;
            let json_module = py.import("json")?;
            let loads = json_module.getattr("loads")?;
            let py_val = loads.call1((py_value,))?;
            py_dict.set_item(key, py_val)?;
        }

        Ok(py_dict.into())
    }

    /// Internal method: Set a property value.
    #[pyo3(name = "_set_property")]
    fn set_property(&mut self, key: String, json_str: String) -> PyResult<()> {
        let value: serde_json::Value = serde_json::from_str(&json_str)
            .map_err(|e| exceptions::PyValueError::new_err(format!("JSON error: {}", e)))?;
        self.location.properties_mut().insert(key, value);
        Ok(())
    }

    /// Internal method: Remove a property.
    #[pyo3(name = "_remove_property")]
    fn remove_property(&mut self, key: String) -> PyResult<()> {
        self.location.properties_mut().remove(&key)
            .ok_or_else(|| exceptions::PyKeyError::new_err(format!("Key '{}' not found", key)))?;
        Ok(())
    }

    /// Export to GeoJSON Feature format.
    ///
    /// Returns:
    ///     dict: GeoJSON Feature object
    fn to_geojson(&self, py: Python) -> PyResult<Py<PyAny>> {
        let geojson = self.location.to_geojson();
        let json_str = serde_json::to_string(&geojson)
            .map_err(|e| exceptions::PyValueError::new_err(format!("JSON error: {}", e)))?;

        let json_module = py.import("json")?;
        let loads = json_module.getattr("loads")?;
        let result = loads.call1((json_str,))?;
        Ok(result.into())
    }

    /// Add a custom property (builder pattern).
    ///
    /// Args:
    ///     key (str): Property name
    ///     value (Any): Property value (must be JSON-serializable)
    ///
    /// Returns:
    ///     PolygonLocation: Self for chaining
    fn add_property<'py>(mut slf: PyRefMut<'py, Self>, key: String, value: &Bound<'py, PyAny>) -> PyResult<PyRefMut<'py, Self>> {
        // Convert Python value to serde_json::Value
        let json_str = Python::attach(|py| -> PyResult<String> {
            let json_module = py.import("json")?;
            let dumps = json_module.getattr("dumps")?;
            let json_str = dumps.call1((value,))?;
            json_str.extract()
        })?;

        let json_value: serde_json::Value = serde_json::from_str(&json_str)
            .map_err(|e| exceptions::PyValueError::new_err(format!("Invalid JSON: {}", e)))?;

        slf.location = slf.location.clone().add_property(&key, json_value);
        Ok(slf)
    }

    // ===== Identifiable trait methods =====

    /// Set the name (builder pattern).
    ///
    /// Args:
    ///     name (str): Human-readable name
    ///
    /// Returns:
    ///     PolygonLocation: Self for chaining
    fn with_name(mut slf: PyRefMut<'_, Self>, name: String) -> PyRefMut<'_, Self> {
        slf.location = slf.location.clone().with_name(&name);
        slf
    }

    /// Set the numeric ID (builder pattern).
    ///
    /// Args:
    ///     id (int): Numeric identifier
    ///
    /// Returns:
    ///     PolygonLocation: Self for chaining
    fn with_id(mut slf: PyRefMut<'_, Self>, id: u64) -> PyRefMut<'_, Self> {
        slf.location = slf.location.clone().with_id(id);
        slf
    }

    /// Set the UUID from a string (builder pattern).
    ///
    /// Args:
    ///     uuid_str (str): UUID string
    ///
    /// Returns:
    ///     PolygonLocation: Self for chaining
    ///
    /// Raises:
    ///     ValueError: If UUID string is invalid
    fn with_uuid(mut slf: PyRefMut<'_, Self>, uuid_str: String) -> PyResult<PyRefMut<'_, Self>> {
        let uuid = uuid::Uuid::parse_str(&uuid_str)
            .map_err(|e| exceptions::PyValueError::new_err(format!("Invalid UUID: {}", e)))?;
        slf.location = slf.location.clone().with_uuid(uuid);
        Ok(slf)
    }

    /// Generate a new UUID (builder pattern).
    ///
    /// Returns:
    ///     PolygonLocation: Self for chaining
    fn with_new_uuid(mut slf: PyRefMut<'_, Self>) -> PyRefMut<'_, Self> {
        slf.location = slf.location.clone().with_new_uuid();
        slf
    }

    /// Get the name.
    ///
    /// Returns:
    ///     str | None: Name if set, None otherwise
    fn get_name(&self) -> Option<String> {
        self.location.get_name().map(|s| s.to_string())
    }

    /// Get the numeric ID.
    ///
    /// Returns:
    ///     int | None: ID if set, None otherwise
    fn get_id(&self) -> Option<u64> {
        self.location.get_id()
    }

    /// Get the UUID as a string.
    ///
    /// Returns:
    ///     str | None: UUID string if set, None otherwise
    fn get_uuid(&self) -> Option<String> {
        self.location.get_uuid().map(|u| u.to_string())
    }

    /// Set the name (mutating).
    ///
    /// Args:
    ///     name (str | None): Name to set, or None to clear
    fn set_name(&mut self, name: Option<String>) {
        self.location.set_name(name.as_deref());
    }

    /// Set the numeric ID (mutating).
    ///
    /// Args:
    ///     id (int | None): ID to set, or None to clear
    fn set_id(&mut self, id: Option<u64>) {
        self.location.set_id(id);
    }

    /// Generate a new UUID (mutating).
    fn generate_uuid(&mut self) {
        self.location.generate_uuid();
    }

    fn __str__(&self) -> String {
        if let Some(name) = self.location.get_name() {
            format!("PolygonLocation({}, {} vertices, center=[{:.4}°, {:.4}°, {:.1}m])",
                name, self.location.num_vertices(),
                self.location.lon(), self.location.lat(), self.location.alt())
        } else {
            format!("PolygonLocation({} vertices, center=[{:.4}°, {:.4}°, {:.1}m])",
                self.location.num_vertices(),
                self.location.lon(), self.location.lat(), self.location.alt())
        }
    }

    fn __repr__(&self) -> String {
        self.__str__()
    }
}

// ================================
// Access Properties
// ================================

/// A flexible value type for access properties.
///
/// PropertyValue can store different types of data associated with access windows,
/// including scalars, vectors, time series, booleans, strings, and arbitrary JSON.
///
/// Args:
///     value: The value to store (int, float, list, bool, str, or dict)
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Scalar value
///     prop1 = bh.PropertyValue(42.5)
///
///     # Vector value
///     prop2 = bh.PropertyValue([1.0, 2.0, 3.0])
///
///     # Boolean value
///     prop3 = bh.PropertyValue(True)
///
///     # String value
///     prop4 = bh.PropertyValue("visible")
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "PropertyValue")]
pub struct PyPropertyValue {
    pub(crate) value: PropertyValue,
}

#[pymethods]
impl PyPropertyValue {
    #[new]
    fn new(value: &Bound<'_, PyAny>) -> PyResult<Self> {
        // Check bool BEFORE f64, since bool is a subclass of int in Python
        let property_value = if let Ok(v) = value.extract::<bool>() {
            PropertyValue::Boolean(v)
        } else if let Ok(v) = value.extract::<f64>() {
            PropertyValue::Scalar(v)
        } else if let Ok(v) = value.extract::<Vec<f64>>() {
            PropertyValue::Vector(v)
        } else if let Ok(v) = value.extract::<String>() {
            PropertyValue::String(v)
        } else if let Ok(dict) = value.cast::<PyDict>() {
            // Convert dict to JSON
            let json_module = value.py().import("json")?;
            let dumps = json_module.getattr("dumps")?;
            let json_str: String = dumps.call1((dict,))?.extract()?;
            let json_value: serde_json::Value = serde_json::from_str(&json_str)
                .map_err(|e| PyErr::new::<exceptions::PyValueError, _>(format!("JSON error: {}", e)))?;
            PropertyValue::Json(json_value)
        } else {
            return Err(PyErr::new::<exceptions::PyTypeError, _>(
                "PropertyValue must be a number, list, bool, str, or dict"
            ));
        };

        Ok(Self { value: property_value })
    }

    /// Convert the property value to a Python object.
    ///
    /// Returns:
    ///     The value as a Python object (int, float, list, bool, or str)
    fn to_python(&self, py: Python) -> PyResult<Py<PyAny>> {
        match &self.value {
            PropertyValue::Scalar(v) => {
                let float_obj = PyFloat::new(py, *v);
                Ok(float_obj.unbind().into())
            }
            PropertyValue::Vector(v) => {
                let list = PyList::new(py, v.iter())?;
                Ok(list.unbind().into())
            }
            PropertyValue::TimeSeries { times, values } => {
                let dict = PyDict::new(py);
                dict.set_item("times", times)?;
                dict.set_item("values", values)?;
                Ok(dict.into())
            }
            PropertyValue::Boolean(v) => {
                // Use Python's builtin bool function
                let builtins = py.import("builtins")?;
                let bool_func = builtins.getattr("bool")?;
                Ok(bool_func.call1((*v,))?.into())
            }
            PropertyValue::String(v) => {
                let str_obj = PyString::new(py, v);
                Ok(str_obj.unbind().into())
            }
            PropertyValue::Json(v) => {
                // Convert JSON to Python via json module
                let json_module = py.import("json")?;
                let loads = json_module.getattr("loads")?;
                let json_str = serde_json::to_string(v)
                    .map_err(|e| PyErr::new::<exceptions::PyValueError, _>(format!("JSON error: {}", e)))?;
                Ok(loads.call1((json_str,))?.into())
            }
        }
    }

    fn __repr__(&self, py: Python) -> PyResult<String> {
        let value_str = self.to_python(py)?;
        Ok(format!("PropertyValue({})", value_str))
    }
}

/// An access window representing a period of time when access constraints are satisfied.
///
/// AccessWindow stores the opening and closing times of an access period, along with
/// computed properties for that window.
///
/// Args:
///     window_open (Epoch): Opening time of the access window
///     window_close (Epoch): Closing time of the access window
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Create an access window
///     t_open = bh.Epoch(2024, 1, 1, 12, 0, 0.0)
///     t_close = bh.Epoch(2024, 1, 1, 12, 10, 0.0)
///     window = bh.AccessWindow(t_open, t_close)
///
///     # Access window properties
///     print(f"Duration: {window.duration()} seconds")
///     print(f"Midpoint: {window.midtime()}")
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "AccessWindow")]
pub struct PyAccessWindow {
    pub(crate) window: AccessWindow,
}

#[pymethods]
impl PyAccessWindow {
    #[new]
    fn new(window_open: &PyEpoch, window_close: &PyEpoch) -> Self {
        Self {
            window: AccessWindow {
                window_open: window_open.obj,
                window_close: window_close.obj,
                location_name: None,
                location_id: None,
                location_uuid: None,
                satellite_name: None,
                satellite_id: None,
                satellite_uuid: None,
                name: None,
                id: None,
                uuid: None,
                properties: AccessProperties {
                    azimuth_open: 0.0,
                    azimuth_close: 0.0,
                    elevation_min: 0.0,
                    elevation_max: 0.0,
                    elevation_open: 0.0,
                    elevation_close: 0.0,
                    off_nadir_min: 0.0,
                    off_nadir_max: 0.0,
                    local_time: 0.0,
                    look_direction: LookDirection::Either,
                    asc_dsc: AscDsc::Either,
                    center_lon: 0.0,
                    center_lat: 0.0,
                    center_alt: 0.0,
                    center_ecef: [0.0, 0.0, 0.0],
                    additional: std::collections::HashMap::new(),
                },
            },
        }
    }

    // ===== Time properties (as getters) =====

    /// Get the window opening time.
    ///
    /// Returns:
    ///     Epoch: Window opening time
    #[getter]
    fn window_open(&self) -> PyEpoch {
        PyEpoch { obj: self.window.window_open }
    }

    /// Get the window closing time.
    ///
    /// Returns:
    ///     Epoch: Window closing time
    #[getter]
    fn window_close(&self) -> PyEpoch {
        PyEpoch { obj: self.window.window_close }
    }

    /// Get the start time of the access window (alias for window_open).
    ///
    /// Returns:
    ///     Epoch: Opening time of the window
    #[getter]
    fn start(&self) -> PyEpoch {
        PyEpoch { obj: self.window.start() }
    }

    /// Get the end time of the access window (alias for window_close).
    ///
    /// Returns:
    ///     Epoch: Closing time of the window
    #[getter]
    fn end(&self) -> PyEpoch {
        PyEpoch { obj: self.window.end() }
    }

    /// Get the start time of the access window (alias for window_open/start).
    ///
    /// Returns:
    ///     Epoch: Opening time of the window
    #[getter]
    fn t_start(&self) -> PyEpoch {
        PyEpoch { obj: self.window.t_start() }
    }

    /// Get the end time of the access window (alias for window_close/end).
    ///
    /// Returns:
    ///     Epoch: Closing time of the window
    #[getter]
    fn t_end(&self) -> PyEpoch {
        PyEpoch { obj: self.window.t_end() }
    }

    /// Get the midpoint time of the access window.
    ///
    /// Returns:
    ///     Epoch: Midpoint time (average of start and end)
    #[getter]
    fn midtime(&self) -> PyEpoch {
        PyEpoch { obj: self.window.midtime() }
    }

    /// Get the duration of the access window in seconds.
    ///
    /// Returns:
    ///     float: Duration in seconds
    #[getter]
    fn duration(&self) -> f64 {
        self.window.duration()
    }

    // ===== Identifiable properties =====

    /// Get the access window name (auto-generated or user-set).
    ///
    /// Returns:
    ///     Optional[str]: Window name, or None if not set
    #[getter]
    fn name(&self) -> Option<String> {
        self.window.name.clone()
    }

    /// Get the access window numeric ID.
    ///
    /// Returns:
    ///     Optional[int]: Window ID, or None if not set
    #[getter]
    fn id(&self) -> Option<u64> {
        self.window.id
    }

    /// Get the access window UUID.
    ///
    /// Returns:
    ///     Optional[str]: UUID as string, or None if not set
    #[getter]
    fn uuid(&self) -> Option<String> {
        self.window.uuid.map(|u| u.to_string())
    }

    // ===== Location/Satellite identification =====

    /// Get the location name if available.
    ///
    /// Returns:
    ///     Optional[str]: Name of the location, or None if not set
    #[getter]
    fn location_name(&self) -> Option<String> {
        self.window.location_name.clone()
    }

    /// Get the location ID if available.
    ///
    /// Returns:
    ///     Optional[int]: ID of the location, or None if not set
    #[getter]
    fn location_id(&self) -> Option<u64> {
        self.window.location_id
    }

    /// Get the satellite/object name if available.
    ///
    /// Returns:
    ///     Optional[str]: Name of the satellite, or None if not set
    #[getter]
    fn satellite_name(&self) -> Option<String> {
        self.window.satellite_name.clone()
    }

    /// Get the satellite/object ID if available.
    ///
    /// Returns:
    ///     Optional[int]: ID of the satellite, or None if not set
    #[getter]
    fn satellite_id(&self) -> Option<u64> {
        self.window.satellite_id
    }

    /// Get the location UUID if available.
    ///
    /// Returns:
    ///     Optional[str]: UUID of the location as string, or None if not set
    #[getter]
    fn location_uuid(&self) -> Option<String> {
        self.window.location_uuid.map(|u| u.to_string())
    }

    /// Get the satellite UUID if available.
    ///
    /// Returns:
    ///     Optional[str]: UUID of the satellite as string, or None if not set
    #[getter]
    fn satellite_uuid(&self) -> Option<String> {
        self.window.satellite_uuid.map(|u| u.to_string())
    }

    // ===== Access properties (convenience getters) =====

    /// Get the access properties as a live view.
    ///
    /// Returns a proxy that delegates reads and writes back to this window,
    /// so mutations to additional properties persist.
    ///
    /// Returns:
    ///     AccessPropertiesView: Live view into this window's properties
    #[getter]
    fn properties(slf: Bound<'_, Self>) -> PyResult<Py<PyAccessPropertiesView>> {
        let py = slf.py();
        let view = PyAccessPropertiesView { parent: slf.into_any().unbind() };
        Py::new(py, view)
    }

    /// Set the access properties object.
    ///
    /// Args:
    ///     value (AccessProperties): New properties for this access window
    #[setter]
    fn set_properties(&mut self, value: PyAccessProperties) {
        self.window.properties = value.properties;
    }

    /// Get azimuth angle at window opening (degrees, 0-360).
    ///
    /// Returns:
    ///     float: Azimuth at window open
    #[getter]
    fn azimuth_open(&self) -> f64 {
        self.window.properties.azimuth_open
    }

    /// Get azimuth angle at window closing (degrees, 0-360).
    ///
    /// Returns:
    ///     float: Azimuth at window close
    #[getter]
    fn azimuth_close(&self) -> f64 {
        self.window.properties.azimuth_close
    }

    /// Get minimum elevation angle during access (degrees).
    ///
    /// Returns:
    ///     float: Minimum elevation angle
    #[getter]
    fn elevation_min(&self) -> f64 {
        self.window.properties.elevation_min
    }

    /// Get maximum elevation angle during access (degrees).
    ///
    /// Returns:
    ///     float: Maximum elevation angle
    #[getter]
    fn elevation_max(&self) -> f64 {
        self.window.properties.elevation_max
    }

    /// Get elevation angle at window opening (degrees).
    ///
    /// Returns:
    ///     float: Elevation at window open
    #[getter]
    fn elevation_open(&self) -> f64 {
        self.window.properties.elevation_open
    }

    /// Get elevation angle at window closing (degrees).
    ///
    /// Returns:
    ///     float: Elevation at window close
    #[getter]
    fn elevation_close(&self) -> f64 {
        self.window.properties.elevation_close
    }

    /// Get minimum off-nadir angle during access (degrees).
    ///
    /// Returns:
    ///     float: Minimum off-nadir angle
    #[getter]
    fn off_nadir_min(&self) -> f64 {
        self.window.properties.off_nadir_min
    }

    /// Get maximum off-nadir angle during access (degrees).
    ///
    /// Returns:
    ///     float: Maximum off-nadir angle
    #[getter]
    fn off_nadir_max(&self) -> f64 {
        self.window.properties.off_nadir_max
    }

    /// Get local solar time at window midpoint (seconds since midnight, 0-86400).
    ///
    /// Returns:
    ///     float: Local time in seconds
    #[getter]
    fn local_time(&self) -> f64 {
        self.window.properties.local_time
    }

    /// Get look direction (Left or Right).
    ///
    /// Returns:
    ///     LookDirection: Look direction enum value
    #[getter]
    fn look_direction(&self) -> PyLookDirection {
        PyLookDirection { value: self.window.properties.look_direction }
    }

    /// Get ascending/descending pass type.
    ///
    /// Returns:
    ///     AscDsc: Pass type enum value
    #[getter]
    fn asc_dsc(&self) -> PyAscDsc {
        PyAscDsc { value: self.window.properties.asc_dsc }
    }

    /// Get location center longitude (degrees).
    ///
    /// Returns:
    ///     float: Longitude in degrees
    #[getter]
    fn center_lon(&self) -> f64 {
        self.window.properties.center_lon
    }

    /// Get location center latitude (degrees).
    ///
    /// Returns:
    ///     float: Latitude in degrees
    #[getter]
    fn center_lat(&self) -> f64 {
        self.window.properties.center_lat
    }

    /// Get location center altitude (meters).
    ///
    /// Returns:
    ///     float: Altitude in meters
    #[getter]
    fn center_alt(&self) -> f64 {
        self.window.properties.center_alt
    }

    /// Get location center ECEF coordinates (meters).
    ///
    /// Returns:
    ///     list[float]: ECEF coordinates [x, y, z] in meters
    #[getter]
    fn center_ecef(&self) -> [f64; 3] {
        self.window.properties.center_ecef
    }

    fn __repr__(&self) -> String {
        format!(
            "AccessWindow(start={}, end={}, duration={:.2}s)",
            self.window.start(),
            self.window.end(),
            self.window.duration()
        )
    }

    // ===== Internal delegation methods for PyAccessPropertiesView =====

    fn _get_properties_azimuth_open(&self) -> f64 {
        self.window.properties.azimuth_open
    }

    fn _get_properties_azimuth_close(&self) -> f64 {
        self.window.properties.azimuth_close
    }

    fn _get_properties_elevation_min(&self) -> f64 {
        self.window.properties.elevation_min
    }

    fn _get_properties_elevation_max(&self) -> f64 {
        self.window.properties.elevation_max
    }

    fn _get_properties_elevation_open(&self) -> f64 {
        self.window.properties.elevation_open
    }

    fn _get_properties_elevation_close(&self) -> f64 {
        self.window.properties.elevation_close
    }

    fn _get_properties_off_nadir_min(&self) -> f64 {
        self.window.properties.off_nadir_min
    }

    fn _get_properties_off_nadir_max(&self) -> f64 {
        self.window.properties.off_nadir_max
    }

    fn _get_properties_local_time(&self) -> f64 {
        self.window.properties.local_time
    }

    fn _get_properties_look_direction(&self) -> PyLookDirection {
        PyLookDirection { value: self.window.properties.look_direction }
    }

    fn _get_properties_asc_dsc(&self) -> PyAscDsc {
        PyAscDsc { value: self.window.properties.asc_dsc }
    }

    fn _get_properties_center_lon(&self) -> f64 {
        self.window.properties.center_lon
    }

    fn _get_properties_center_lat(&self) -> f64 {
        self.window.properties.center_lat
    }

    fn _get_properties_center_alt(&self) -> f64 {
        self.window.properties.center_alt
    }

    fn _get_properties_center_ecef(&self) -> [f64; 3] {
        self.window.properties.center_ecef
    }

    fn _get_additional_properties_dict(&self, py: Python) -> PyResult<Py<PyDict>> {
        let dict = PyDict::new(py);
        for (key, value) in &self.window.properties.additional {
            let py_value: Py<PyAny> = match value {
                PropertyValue::Scalar(v) => {
                    let float_obj = PyFloat::new(py, *v);
                    float_obj.unbind().into()
                }
                PropertyValue::Vector(v) => {
                    let list = PyList::new(py, v.iter())?;
                    list.unbind().into()
                }
                PropertyValue::TimeSeries { times, values } => {
                    let ts_dict = PyDict::new(py);
                    ts_dict.set_item("times", times)?;
                    ts_dict.set_item("values", values)?;
                    ts_dict.into()
                }
                PropertyValue::Boolean(v) => {
                    let builtins = py.import("builtins")?;
                    let bool_func = builtins.getattr("bool")?;
                    bool_func.call1((*v,))?.into()
                }
                PropertyValue::String(v) => {
                    let str_obj = PyString::new(py, v);
                    str_obj.unbind().into()
                }
                PropertyValue::Json(v) => {
                    let json_module = py.import("json")?;
                    let loads = json_module.getattr("loads")?;
                    let json_str = serde_json::to_string(v)
                        .map_err(|e| PyErr::new::<exceptions::PyValueError, _>(format!("JSON error: {}", e)))?;
                    loads.call1((json_str,))?.into()
                }
            };
            dict.set_item(key, py_value)?;
        }
        Ok(dict.into())
    }

    fn _set_additional_property(&mut self, key: String, value: &Bound<'_, PyAny>) -> PyResult<()> {
        let property_value = if let Ok(v) = value.extract::<bool>() {
            PropertyValue::Boolean(v)
        } else if let Ok(v) = value.extract::<f64>() {
            PropertyValue::Scalar(v)
        } else if let Ok(v) = value.extract::<Vec<f64>>() {
            PropertyValue::Vector(v)
        } else if value.hasattr("tolist")? {
            let as_list = value.call_method0("tolist")?;
            if let Ok(v) = as_list.extract::<Vec<f64>>() {
                PropertyValue::Vector(v)
            } else {
                return Err(PyErr::new::<exceptions::PyTypeError, _>(
                    "Numpy array must contain numeric values"
                ));
            }
        } else if let Ok(v) = value.extract::<String>() {
            PropertyValue::String(v)
        } else if let Ok(dict) = value.cast::<PyDict>() {
            let json_module = value.py().import("json")?;
            let dumps = json_module.getattr("dumps")?;
            let json_str: String = dumps.call1((dict,))?.extract()?;
            let json_value: serde_json::Value = serde_json::from_str(&json_str)
                .map_err(|e| PyErr::new::<exceptions::PyValueError, _>(format!("JSON error: {}", e)))?;
            PropertyValue::Json(json_value)
        } else {
            return Err(PyErr::new::<exceptions::PyTypeError, _>(
                "Property value must be a number, list, numpy array, bool, str, or dict"
            ));
        };

        self.window.properties.additional.insert(key, property_value);
        Ok(())
    }

    fn _remove_additional_property(&mut self, key: String) -> PyResult<()> {
        self.window.properties.additional.remove(&key)
            .ok_or_else(|| exceptions::PyKeyError::new_err(format!("Key '{}' not found", key)))?;
        Ok(())
    }
}

// ================================
// AccessPropertiesView
// ================================

/// A proxy view into the properties of an AccessWindow.
///
/// This view delegates all reads and writes back to the parent AccessWindow,
/// ensuring that mutations (especially to additional properties) persist.
/// Returned by AccessWindow.properties getter.
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "AccessPropertiesView")]
pub struct PyAccessPropertiesView {
    parent: Py<PyAny>,
}

#[pymethods]
impl PyAccessPropertiesView {
    #[getter]
    fn azimuth_open(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_azimuth_open")?.extract()
    }

    #[getter]
    fn azimuth_close(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_azimuth_close")?.extract()
    }

    #[getter]
    fn elevation_min(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_elevation_min")?.extract()
    }

    #[getter]
    fn elevation_max(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_elevation_max")?.extract()
    }

    #[getter]
    fn elevation_open(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_elevation_open")?.extract()
    }

    #[getter]
    fn elevation_close(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_elevation_close")?.extract()
    }

    #[getter]
    fn off_nadir_min(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_off_nadir_min")?.extract()
    }

    #[getter]
    fn off_nadir_max(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_off_nadir_max")?.extract()
    }

    #[getter]
    fn local_time(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_local_time")?.extract()
    }

    #[getter]
    fn look_direction(&self, py: Python) -> PyResult<Py<PyAny>> {
        let parent = self.parent.bind(py);
        Ok(parent.call_method0("_get_properties_look_direction")?.unbind())
    }

    #[getter]
    fn asc_dsc(&self, py: Python) -> PyResult<Py<PyAny>> {
        let parent = self.parent.bind(py);
        Ok(parent.call_method0("_get_properties_asc_dsc")?.unbind())
    }

    #[getter]
    fn center_lon(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_center_lon")?.extract()
    }

    #[getter]
    fn center_lat(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_center_lat")?.extract()
    }

    #[getter]
    fn center_alt(&self, py: Python) -> PyResult<f64> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_center_alt")?.extract()
    }

    #[getter]
    fn center_ecef(&self, py: Python) -> PyResult<[f64; 3]> {
        let parent = self.parent.bind(py);
        parent.call_method0("_get_properties_center_ecef")?.extract()
    }

    /// Get additional properties as a dict-like wrapper.
    ///
    /// Returns:
    ///     AdditionalPropertiesDict: Dict-like wrapper for additional properties
    #[getter]
    fn additional(slf: Bound<'_, Self>) -> PyResult<Py<PyAdditionalPropertiesDict>> {
        let py = slf.py();
        let dict = PyAdditionalPropertiesDict::new(slf.into_any().unbind());
        Py::new(py, dict)
    }

    /// Get a property value by key (convenience for additional properties).
    fn __getitem__(&self, key: String, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self._get_additional_properties_dict(py)?;
        let dict = props_dict.bind(py);
        dict.get_item(&key)?
            .ok_or_else(|| exceptions::PyKeyError::new_err(format!("Key '{}' not found", key)))
            .map(|item| item.into())
    }

    /// Set a property value by key (convenience for additional properties).
    fn __setitem__(&self, key: String, value: &Bound<'_, PyAny>, py: Python) -> PyResult<()> {
        let parent = self.parent.bind(py);
        parent.call_method1("_set_additional_property", (key, value))?;
        Ok(())
    }

    // Internal methods for AdditionalPropertiesDict to chain through the view
    fn _get_additional_properties_dict(&self, py: Python) -> PyResult<Py<PyDict>> {
        let parent = self.parent.bind(py);
        let result = parent.call_method0("_get_additional_properties_dict")?;
        Ok(result.extract()?)
    }

    fn _set_additional_property(&self, key: String, value: &Bound<'_, PyAny>, py: Python) -> PyResult<()> {
        let parent = self.parent.bind(py);
        parent.call_method1("_set_additional_property", (key, value))?;
        Ok(())
    }

    fn _remove_additional_property(&self, key: String, py: Python) -> PyResult<()> {
        let parent = self.parent.bind(py);
        parent.call_method1("_remove_additional_property", (key,))?;
        Ok(())
    }

    fn __repr__(&self, py: Python) -> PyResult<String> {
        let az_open: f64 = self.parent.bind(py).call_method0("_get_properties_azimuth_open")?.extract()?;
        let az_close: f64 = self.parent.bind(py).call_method0("_get_properties_azimuth_close")?.extract()?;
        let el_min: f64 = self.parent.bind(py).call_method0("_get_properties_elevation_min")?.extract()?;
        let el_max: f64 = self.parent.bind(py).call_method0("_get_properties_elevation_max")?.extract()?;
        let on_min: f64 = self.parent.bind(py).call_method0("_get_properties_off_nadir_min")?.extract()?;
        let on_max: f64 = self.parent.bind(py).call_method0("_get_properties_off_nadir_max")?.extract()?;
        Ok(format!(
            "AccessPropertiesView(az=[{:.1}°, {:.1}°], el=[{:.1}°, {:.1}°], off_nadir=[{:.1}°, {:.1}°])",
            az_open, az_close, el_min, el_max, on_min, on_max
        ))
    }
}

/// Properties computed for an access window.
///
/// AccessProperties contains geometric properties (azimuth, elevation, off-nadir angles,
/// local time, look direction, ascending/descending) computed over an access window,
/// plus location coordinates, plus a dictionary of additional custom properties.
///
/// Attributes:
///     azimuth_open (float): Azimuth angle at window opening (degrees, 0-360)
///     azimuth_close (float): Azimuth angle at window closing (degrees, 0-360)
///     elevation_min (float): Minimum elevation angle (degrees)
///     elevation_max (float): Maximum elevation angle (degrees)
///     elevation_open (float): Elevation angle at window opening (degrees)
///     elevation_close (float): Elevation angle at window closing (degrees)
///     off_nadir_min (float): Minimum off-nadir angle (degrees)
///     off_nadir_max (float): Maximum off-nadir angle (degrees)
///     local_time (float): Local solar time (seconds since midnight, 0-86400)
///     look_direction (LookDirection): Required look direction (Left or Right)
///     asc_dsc (AscDsc): Pass type (Ascending or Descending)
///     center_lon (float): Location center longitude (degrees)
///     center_lat (float): Location center latitude (degrees)
///     center_alt (float): Location center altitude (meters)
///     center_ecef (list[float]): Location center ECEF coordinates [x, y, z] (meters)
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Access properties are typically computed by the access computation system
///     # This example shows accessing the properties
///     props = ...  # From access computation
///
///     print(f"Azimuth at open: {props.azimuth_open}°")
///     print(f"Max elevation: {props.elevation_max}°")
///     print(f"Look direction: {props.look_direction}")
///
///     # Access additional custom properties
///     if "signal_strength" in props.additional:
///         print(f"Signal: {props.additional['signal_strength']}")
///     ```
#[derive(Clone)]
#[pyclass(module = "brahe._brahe", from_py_object)]
#[pyo3(name = "AccessProperties")]
pub struct PyAccessProperties {
    pub(crate) properties: AccessProperties,
}

#[pymethods]
impl PyAccessProperties {
    #[new]
    #[allow(clippy::too_many_arguments)]
    fn new(
        azimuth_open: f64,
        azimuth_close: f64,
        elevation_min: f64,
        elevation_max: f64,
        elevation_open: f64,
        elevation_close: f64,
        off_nadir_min: f64,
        off_nadir_max: f64,
        local_time: f64,
        look_direction: &PyLookDirection,
        asc_dsc: &PyAscDsc,
        center_lon: f64,
        center_lat: f64,
        center_alt: f64,
        center_ecef: [f64; 3],
    ) -> Self {
        Self {
            properties: AccessProperties {
                azimuth_open,
                azimuth_close,
                elevation_min,
                elevation_max,
                elevation_open,
                elevation_close,
                off_nadir_min,
                off_nadir_max,
                local_time,
                look_direction: look_direction.value,
                asc_dsc: asc_dsc.value,
                center_lon,
                center_lat,
                center_alt,
                center_ecef,
                additional: std::collections::HashMap::new(),
            },
        }
    }

    #[getter]
    fn azimuth_open(&self) -> f64 {
        self.properties.azimuth_open
    }

    #[getter]
    fn azimuth_close(&self) -> f64 {
        self.properties.azimuth_close
    }

    #[getter]
    fn elevation_min(&self) -> f64 {
        self.properties.elevation_min
    }

    #[getter]
    fn elevation_max(&self) -> f64 {
        self.properties.elevation_max
    }

    #[getter]
    fn elevation_open(&self) -> f64 {
        self.properties.elevation_open
    }

    #[getter]
    fn elevation_close(&self) -> f64 {
        self.properties.elevation_close
    }

    #[getter]
    fn off_nadir_min(&self) -> f64 {
        self.properties.off_nadir_min
    }

    #[getter]
    fn off_nadir_max(&self) -> f64 {
        self.properties.off_nadir_max
    }

    #[getter]
    fn local_time(&self) -> f64 {
        self.properties.local_time
    }

    #[getter]
    fn look_direction(&self) -> PyLookDirection {
        PyLookDirection { value: self.properties.look_direction }
    }

    #[getter]
    fn asc_dsc(&self) -> PyAscDsc {
        PyAscDsc { value: self.properties.asc_dsc }
    }

    /// Get location center longitude (degrees).
    ///
    /// Returns:
    ///     float: Longitude in degrees
    #[getter]
    fn center_lon(&self) -> f64 {
        self.properties.center_lon
    }

    /// Get location center latitude (degrees).
    ///
    /// Returns:
    ///     float: Latitude in degrees
    #[getter]
    fn center_lat(&self) -> f64 {
        self.properties.center_lat
    }

    #[getter]
    fn center_alt(&self) -> f64 {
        self.properties.center_alt
    }

    #[getter]
    fn center_ecef(&self) -> [f64; 3] {
        self.properties.center_ecef
    }

    /// Get additional properties as a dict-like wrapper.
    ///
    /// Returns a dictionary-like object that automatically converts between
    /// Python types and internal PropertyValue representation.
    ///
    /// Supported Python types:
    /// - float -> Scalar
    /// - list[float] -> Vector
    /// - bool -> Boolean
    /// - str -> String
    /// - dict -> Json
    ///
    /// Returns:
    ///     AdditionalPropertiesDict: Dict-like wrapper for additional properties
    ///
    /// Example:
    ///     ```python
    ///     # Dict-style assignment
    ///     props.additional["doppler_shift"] = 2500.0
    ///     props.additional["snr_values"] = [10.5, 12.3, 15.1]
    ///     props.additional["has_eclipse"] = False
    ///
    ///     # Dict-style access
    ///     print(props.additional["doppler_shift"])  # 2500.0
    ///
    ///     # Dict methods
    ///     if "doppler_shift" in props.additional:
    ///         del props.additional["doppler_shift"]
    ///
    ///     # Iteration
    ///     for key in props.additional.keys():
    ///         print(key, props.additional[key])
    ///     ```
    #[getter]
    fn additional(slf: Bound<'_, Self>) -> PyResult<Py<PyAdditionalPropertiesDict>> {
        let py = slf.py();
        let dict = PyAdditionalPropertiesDict::new(slf.into_any().unbind());
        Py::new(py, dict)
    }

    // Internal methods for AdditionalPropertiesDict to call back into
    fn _get_additional_properties_dict(&self, py: Python) -> PyResult<Py<PyDict>> {
        let dict = PyDict::new(py);
        for (key, value) in &self.properties.additional {
            let py_value: Py<PyAny> = match value {
                PropertyValue::Scalar(v) => {
                    let float_obj = PyFloat::new(py, *v);
                    float_obj.unbind().into()
                }
                PropertyValue::Vector(v) => {
                    let list = PyList::new(py, v.iter())?;
                    list.unbind().into()
                }
                PropertyValue::TimeSeries { times, values } => {
                    let ts_dict = PyDict::new(py);
                    ts_dict.set_item("times", times)?;
                    ts_dict.set_item("values", values)?;
                    ts_dict.into()
                }
                PropertyValue::Boolean(v) => {
                    // Use Python's builtin bool function
                    let builtins = py.import("builtins")?;
                    let bool_func = builtins.getattr("bool")?;
                    bool_func.call1((*v,))?.into()
                }
                PropertyValue::String(v) => {
                    let str_obj = PyString::new(py, v);
                    str_obj.unbind().into()
                }
                PropertyValue::Json(v) => {
                    let json_module = py.import("json")?;
                    let loads = json_module.getattr("loads")?;
                    let json_str = serde_json::to_string(v)
                        .map_err(|e| PyErr::new::<exceptions::PyValueError, _>(format!("JSON error: {}", e)))?;
                    loads.call1((json_str,))?.into()
                }
            };
            dict.set_item(key, py_value)?;
        }
        Ok(dict.into())
    }

    fn _set_additional_property(&mut self, key: String, value: &Bound<'_, PyAny>) -> PyResult<()> {
        // Check bool BEFORE f64, since bool is a subclass of int in Python
        let property_value = if let Ok(v) = value.extract::<bool>() {
            PropertyValue::Boolean(v)
        } else if let Ok(v) = value.extract::<f64>() {
            PropertyValue::Scalar(v)
        } else if let Ok(v) = value.extract::<Vec<f64>>() {
            // Handle regular Python lists
            PropertyValue::Vector(v)
        } else if value.hasattr("tolist")? {
            // Handle numpy arrays by converting to list
            let as_list = value.call_method0("tolist")?;
            if let Ok(v) = as_list.extract::<Vec<f64>>() {
                PropertyValue::Vector(v)
            } else {
                return Err(PyErr::new::<exceptions::PyTypeError, _>(
                    "Numpy array must contain numeric values"
                ));
            }
        } else if let Ok(v) = value.extract::<String>() {
            PropertyValue::String(v)
        } else if let Ok(dict) = value.cast::<PyDict>() {
            // Convert dict to JSON
            let json_module = value.py().import("json")?;
            let dumps = json_module.getattr("dumps")?;
            let json_str: String = dumps.call1((dict,))?.extract()?;
            let json_value: serde_json::Value = serde_json::from_str(&json_str)
                .map_err(|e| PyErr::new::<exceptions::PyValueError, _>(format!("JSON error: {}", e)))?;
            PropertyValue::Json(json_value)
        } else {
            return Err(PyErr::new::<exceptions::PyTypeError, _>(
                "Property value must be a number, list, numpy array, bool, str, or dict"
            ));
        };

        self.properties.additional.insert(key, property_value);
        Ok(())
    }

    fn _remove_additional_property(&mut self, key: String) -> PyResult<()> {
        self.properties.additional.remove(&key)
            .ok_or_else(|| exceptions::PyKeyError::new_err(format!("Key '{}' not found", key)))?;
        Ok(())
    }

    fn __repr__(&self) -> String {
        format!(
            "AccessProperties(az=[{:.1}°, {:.1}°], el=[{:.1}°, {:.1}°], off_nadir=[{:.1}°, {:.1}°])",
            self.properties.azimuth_open,
            self.properties.azimuth_close,
            self.properties.elevation_min,
            self.properties.elevation_max,
            self.properties.off_nadir_min,
            self.properties.off_nadir_max
        )
    }
}

// ================================
// AdditionalPropertiesDict
// ================================

/// Python dictionary interface for additional access properties.
///
/// Provides dict-like access to additional properties with automatic type conversion.
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "AdditionalPropertiesDict")]
pub struct PyAdditionalPropertiesDict {
    parent: Py<PyAny>,
}

#[pymethods]
impl PyAdditionalPropertiesDict {
    /// Get a property value by key.
    fn __getitem__(&self, key: String, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_additional_properties_dict(py)?;
        props_dict
            .get_item(&key)?
            .ok_or_else(|| exceptions::PyKeyError::new_err(format!("Key '{}' not found", key)))
            .map(|item| item.into())
    }

    /// Set a property value by key.
    ///
    /// Args:
    ///     key (str): Property name
    ///     value (Any): Property value (must be JSON-serializable)
    fn __setitem__(&self, key: String, value: &Bound<'_, PyAny>, py: Python) -> PyResult<()> {
        // Call the parent's _set_additional_property method which handles type conversion
        self.set_additional_property(py, key, value)?;
        Ok(())
    }

    /// Delete a property by key.
    fn __delitem__(&self, key: String, py: Python) -> PyResult<()> {
        self.remove_additional_property(py, key)
    }

    /// Return the number of properties.
    fn __len__(&self, py: Python) -> PyResult<usize> {
        let props_dict = self.get_additional_properties_dict(py)?;
        Ok(props_dict.len())
    }

    /// Check if a key exists in properties.
    fn __contains__(&self, key: String, py: Python) -> PyResult<bool> {
        let props_dict = self.get_additional_properties_dict(py)?;
        props_dict.contains(&key)
    }

    /// Return an iterator over property keys.
    fn __iter__(&self, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_additional_properties_dict(py)?;
        Ok(props_dict.call_method0("__iter__")?.into())
    }

    /// String representation.
    fn __repr__(&self, py: Python) -> PyResult<String> {
        let props_dict = self.get_additional_properties_dict(py)?;
        Ok(format!("AdditionalPropertiesDict({})", props_dict.repr()?))
    }

    /// Get property value with optional default.
    ///
    /// Args:
    ///     key (str): Property name
    ///     default (optional): Value to return if key not found
    ///
    /// Returns:
    ///     Any: Property value if key exists, otherwise default value
    #[pyo3(signature = (key, default=None))]
    fn get(&self, key: String, default: Option<Py<PyAny>>, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_additional_properties_dict(py)?;
        match props_dict.get_item(&key)? {
            Some(value) => Ok(value.into()),
            None => Ok(default.unwrap_or_else(|| py.None())),
        }
    }

    /// Return a list of property keys.
    ///
    /// Returns:
    ///     List of property key strings
    fn keys(&self, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_additional_properties_dict(py)?;
        Ok(props_dict.call_method0("keys")?.into())
    }

    /// Return a list of property values.
    ///
    /// Returns:
    ///     List of property values
    fn values(&self, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_additional_properties_dict(py)?;
        Ok(props_dict.call_method0("values")?.into())
    }

    /// Return a list of (key, value) tuples.
    ///
    /// Returns:
    ///     List of (key, value) tuples
    fn items(&self, py: Python) -> PyResult<Py<PyAny>> {
        let props_dict = self.get_additional_properties_dict(py)?;
        Ok(props_dict.call_method0("items")?.into())
    }

    /// Remove all properties.
    ///
    /// Returns:
    ///     None
    fn clear(&self, py: Python) -> PyResult<()> {
        // Get all keys first (to avoid modifying during iteration)
        let props_dict = self.get_additional_properties_dict(py)?;
        let keys_view = props_dict.call_method0("keys")?;

        // Convert dict_keys to list before extracting
        let builtins = py.import("builtins")?;
        let list_fn = builtins.getattr("list")?;
        let keys_list = list_fn.call1((keys_view,))?;
        let keys: Vec<String> = keys_list.extract()?;

        // Remove each key
        for key in keys {
            self.remove_additional_property(py, key)?;
        }
        Ok(())
    }

    /// Update properties from another dict.
    ///
    /// Args:
    ///     other (dict): Dictionary to merge into properties
    ///
    /// Returns:
    ///     None
    fn update(&self, other: &Bound<'_, PyDict>, py: Python) -> PyResult<()> {
        for (key, value) in other.iter() {
            let key_str: String = key.extract()?;
            self.__setitem__(key_str, &value, py)?;
        }
        Ok(())
    }
}

impl PyAdditionalPropertiesDict {
    /// Create a new AdditionalPropertiesDict wrapping a parent AccessProperties.
    fn new(parent: Py<PyAny>) -> Self {
        Self { parent }
    }

    /// Get the additional properties as a Python dict.
    fn get_additional_properties_dict<'a>(&self, py: Python<'a>) -> PyResult<Bound<'a, PyDict>> {
        // Call the parent's internal _get_additional_properties_dict method
        let parent_obj = self.parent.bind(py);
        let props_obj = parent_obj.call_method0("_get_additional_properties_dict")?;
        props_obj.cast::<PyDict>().cloned().map_err(|e| e.into())
    }

    /// Set a property on the parent AccessProperties.
    fn set_additional_property(&self, py: Python, key: String, value: &Bound<'_, PyAny>) -> PyResult<()> {
        let parent_obj = self.parent.bind(py);
        parent_obj.call_method1("_set_additional_property", (key, value))?;
        Ok(())
    }

    /// Remove a property from the parent AccessProperties.
    fn remove_additional_property(&self, py: Python, key: String) -> PyResult<()> {
        let parent_obj = self.parent.bind(py);
        parent_obj.call_method1("_remove_additional_property", (key,))?;
        Ok(())
    }
}

// ================================
// SamplingConfig
// ================================

/// Sampling configuration for access property computation.
///
/// Determines how many times and when to sample satellite states during
/// an access window for property calculations.
///
/// Args:
///     relative_times (list[float], optional): Relative times from 0.0 (start) to 1.0 (end).
///         If provided, uses relative points sampling.
///     interval (float, optional): Time between samples (seconds). If provided with offset,
///         uses fixed interval sampling.
///     offset (float, optional): Time offset from window start (seconds). Used with interval.
///     count (int, optional): Number of evenly-spaced sample points. If provided,
///         uses fixed count sampling.
///
/// Note:
///     If no parameters are provided, defaults to midpoint sampling.
///     Parameters are checked in priority order: relative_times, interval+offset, count.
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Midpoint (default)
///     config = bh.SamplingConfig()
///
///     # Relative points
///     config = bh.SamplingConfig(relative_times=[0.0, 0.5, 1.0])
///
///     # Fixed interval
///     config = bh.SamplingConfig(interval=0.1, offset=0.0)
///
///     # Fixed count
///     config = bh.SamplingConfig(count=10)
///
///     # Or use convenience static methods
///     config = bh.SamplingConfig.midpoint()
///     config = bh.SamplingConfig.relative_points([0.0, 0.5, 1.0])
///     ```
#[pyclass(module = "brahe._brahe", from_py_object)]
#[pyo3(name = "SamplingConfig")]
#[derive(Clone)]
pub struct PySamplingConfig {
    config: SamplingConfig,
}

#[pymethods]
impl PySamplingConfig {
    /// Create a sampling configuration.
    ///
    /// Args:
    ///     relative_times (list[float], optional): Relative times from 0.0 to 1.0.
    ///     interval (float, optional): Time between samples (seconds).
    ///     offset (float, optional): Time offset from window start (seconds).
    ///     count (int, optional): Number of evenly-spaced sample points.
    ///
    /// Returns:
    ///     SamplingConfig: Sampling configuration.
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     # Midpoint (default)
    ///     config = bh.SamplingConfig()
    ///
    ///     # Relative points
    ///     config = bh.SamplingConfig(relative_times=[0.0, 0.5, 1.0])
    ///     ```
    #[new]
    #[pyo3(signature = (relative_times=None, interval=None, offset=None, count=None))]
    fn new(
        relative_times: Option<Vec<f64>>,
        interval: Option<f64>,
        offset: Option<f64>,
        count: Option<usize>,
    ) -> Self {
        let config = if let Some(times) = relative_times {
            SamplingConfig::RelativePoints(times)
        } else if let (Some(int), Some(off)) = (interval, offset) {
            SamplingConfig::FixedInterval { interval: int, offset: off }
        } else if let Some(c) = count {
            SamplingConfig::FixedCount(c)
        } else {
            SamplingConfig::Midpoint
        };
        PySamplingConfig { config }
    }

    /// Create a midpoint sampling configuration (single sample at window center).
    ///
    /// Returns:
    ///     SamplingConfig: Midpoint sampling configuration
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     config = bh.SamplingConfig.midpoint()
    ///     ```
    #[staticmethod]
    fn midpoint() -> Self {
        PySamplingConfig {
            config: SamplingConfig::Midpoint,
        }
    }

    /// Create a relative points sampling configuration.
    ///
    /// Args:
    ///     relative_times (list[float]): Relative times from 0.0 (window start) to 1.0 (window end)
    ///
    /// Returns:
    ///     SamplingConfig: Relative points sampling configuration
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     # Sample at start, quarter, middle, three-quarters, and end
    ///     config = bh.SamplingConfig.relative_points([0.0, 0.25, 0.5, 0.75, 1.0])
    ///     ```
    #[staticmethod]
    fn relative_points(relative_times: Vec<f64>) -> Self {
        PySamplingConfig {
            config: SamplingConfig::RelativePoints(relative_times),
        }
    }

    /// Create a fixed interval sampling configuration.
    ///
    /// Args:
    ///     interval (float): Time between samples (seconds)
    ///     offset (float): Time offset from window start (seconds)
    ///
    /// Returns:
    ///     SamplingConfig: Fixed interval sampling configuration
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     # Sample every 0.1 seconds, starting at window open
    ///     config = bh.SamplingConfig.fixed_interval(0.1, 0.0)
    ///     ```
    #[staticmethod]
    fn fixed_interval(interval: f64, offset: f64) -> Self {
        PySamplingConfig {
            config: SamplingConfig::FixedInterval { interval, offset },
        }
    }

    /// Create a fixed count sampling configuration.
    ///
    /// Args:
    ///     count (int): Number of evenly-spaced sample points (including endpoints)
    ///
    /// Returns:
    ///     SamplingConfig: Fixed count sampling configuration
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     # Sample at 10 evenly-spaced points
    ///     config = bh.SamplingConfig.fixed_count(10)
    ///     ```
    #[staticmethod]
    fn fixed_count(count: usize) -> Self {
        PySamplingConfig {
            config: SamplingConfig::FixedCount(count),
        }
    }

    fn __repr__(&self) -> String {
        match &self.config {
            SamplingConfig::Midpoint => "SamplingConfig.midpoint()".to_string(),
            SamplingConfig::RelativePoints(times) => {
                format!("SamplingConfig.relative_points({:?})", times)
            }
            SamplingConfig::FixedInterval { interval, offset } => {
                format!(
                    "SamplingConfig.fixed_interval(interval={}, offset={})",
                    interval, offset
                )
            }
            SamplingConfig::FixedCount(count) => {
                format!("SamplingConfig.fixed_count({})", count)
            }
        }
    }
}

// ================================
// Property Computers
// ================================

/// Computes Doppler shift during access windows.
///
/// Calculates uplink and/or downlink Doppler shifts based on satellite velocity
/// and line-of-sight geometry.
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Doppler for GPS L1 downlink
///     config = bh.SamplingConfig.midpoint()
///     computer = bh.DopplerComputer(
///         uplink_frequency=None,
///         downlink_frequency=1.57542e9,  # Hz
///         sampling_config=config
///     )
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "DopplerComputer")]
pub struct PyDopplerComputer {
    #[allow(dead_code)]
    computer: DopplerComputer,
}

#[pymethods]
impl PyDopplerComputer {
    /// Create a new Doppler computer.
    ///
    /// Args:
    ///     uplink_frequency (float | None): Uplink frequency in Hz (optional)
    ///     downlink_frequency (float | None): Downlink frequency in Hz (optional)
    ///     sampling_config (SamplingConfig): Sampling configuration
    ///
    /// Returns:
    ///     DopplerComputer: New Doppler computer instance
    ///
    /// Note:
    ///     At least one frequency (uplink or downlink) must be specified.
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     config = bh.SamplingConfig.midpoint()
    ///     computer = bh.DopplerComputer(None, 1.57542e9, config)
    ///     ```
    #[new]
    fn new(
        uplink_frequency: Option<f64>,
        downlink_frequency: Option<f64>,
        sampling_config: &PySamplingConfig,
    ) -> Self {
        PyDopplerComputer {
            computer: DopplerComputer::new(
                uplink_frequency,
                downlink_frequency,
                sampling_config.config.clone(),
            ),
        }
    }

    fn __repr__(&self) -> String {
        format!(
            "DopplerComputer(uplink_frequency={:?}, downlink_frequency={:?})",
            self.computer.uplink_frequency, self.computer.downlink_frequency
        )
    }
}

/// Computes range (distance) during access windows.
///
/// Calculates the distance between satellite and ground location.
///
/// Example:
///     ```python
///     import brahe as bh
///
///     config = bh.SamplingConfig.fixed_interval(0.1 / 86400.0, 0.0)
///     computer = bh.RangeComputer(config)
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "RangeComputer")]
pub struct PyRangeComputer {
    #[allow(dead_code)]
    computer: RangeComputer,
}

#[pymethods]
impl PyRangeComputer {
    /// Create a new range computer.
    ///
    /// Args:
    ///     sampling_config (SamplingConfig): Sampling configuration
    ///
    /// Returns:
    ///     RangeComputer: New range computer instance
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     config = bh.SamplingConfig.midpoint()
    ///     computer = bh.RangeComputer(config)
    ///     ```
    #[new]
    fn new(sampling_config: &PySamplingConfig) -> Self {
        PyRangeComputer {
            computer: RangeComputer::new(sampling_config.config.clone()),
        }
    }

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

/// Computes range rate (radial velocity) during access windows.
///
/// Calculates the rate of change of distance between satellite and ground location.
///
/// Example:
///     ```python
///     import brahe as bh
///
///     config = bh.SamplingConfig.fixed_interval(0.1 / 86400.0, 0.0)
///     computer = bh.RangeRateComputer(config)
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "RangeRateComputer")]
pub struct PyRangeRateComputer {
    #[allow(dead_code)]
    computer: RangeRateComputer,
}

#[pymethods]
impl PyRangeRateComputer {
    /// Create a new range rate computer.
    ///
    /// Args:
    ///     sampling_config (SamplingConfig): Sampling configuration
    ///
    /// Returns:
    ///     RangeRateComputer: New range rate computer instance
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     config = bh.SamplingConfig.midpoint()
    ///     computer = bh.RangeRateComputer(config)
    ///     ```
    #[new]
    fn new(sampling_config: &PySamplingConfig) -> Self {
        PyRangeRateComputer {
            computer: RangeRateComputer::new(sampling_config.config.clone()),
        }
    }

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

// ================================
// AccessPropertyComputer
// ================================

/// Base class for custom access property computers.
///
/// Subclass this class and implement the `compute` and `property_names` methods
/// to create custom property calculations that can be applied to access windows.
///
/// The compute method is called for each access window and should return a dictionary
/// of property names to values. Properties can be scalars, vectors, time series,
/// booleans, strings, or any JSON-serializable value.
///
/// Example:
///     ```python
///     import brahe as bh
///     import numpy as np
///
///     class DopplerComputer(bh.AccessPropertyComputer):
///         '''Computes Doppler shift time series during access windows.'''
///
///         def sampling_config(self) -> bh.SamplingConfig:
///             '''Configure sampling at 1 Hz during access windows.'''
///             return bh.SamplingConfig.fixed_interval(1.0, 0.0)
///
///         def compute(
///             self,
///             window: bh.AccessWindow,
///             sample_epochs: np.ndarray,
///             sample_states_ecef: np.ndarray,
///             location_ecef: np.ndarray,
///             location_geodetic: np.ndarray
///         ) -> dict:
///             '''
///             Args:
///                 window (AccessWindow): AccessWindow with timing information
///                 sample_epochs (ndarray): Sample epochs in MJD [N]
///                 sample_states_ecef (ndarray): Satellite states [N x 6] in ECEF (m, m/s)
///                 location_ecef (ndarray or list): Location position [x,y,z] in ECEF (m)
///                 location_geodetic (ndarray or list): Location geodetic [lon,lat,alt] (deg, deg, m)
///
///             Returns:
///                 dict: Property name -> value (scalar, list, or dict for time series)
///             '''
///             # Compute Doppler shift at each sample
///             doppler_values = []
///             for state in sample_states_ecef:
///                 sat_pos = state[:3]
///                 sat_vel = state[3:6]
///
///                 # Line-of-sight vector
///                 los = sat_pos - location_ecef
///                 los_unit = los / np.linalg.norm(los)
///
///                 # Radial velocity
///                 radial_velocity = np.dot(sat_vel, los_unit)
///
///                 # Doppler shift (L-band)
///                 freq_hz = 1.57542e9  # GPS L1
///                 doppler_hz = -radial_velocity * freq_hz / bh.C_LIGHT
///                 doppler_values.append(doppler_hz)
///
///             # Return time series
///             return {
///                 "doppler_shift": {
///                     "times": sample_epochs.tolist(),
///                     "values": doppler_values
///                 }
///             }
///
///         def property_names(self) -> list:
///             '''Return list of property names this computer produces.'''
///             return ["doppler_shift"]
///
///     # Use with access computation (future)
///     computer = DopplerComputer()
///     # accesses = bh.compute_accesses(..., property_computers=[computer])
///     ```
///
/// Notes:
///     - The `compute` method receives ECEF coordinates in SI units (meters, m/s)
///     - Property values are automatically converted to appropriate Rust types
///     - The window parameter provides access to timing via:
///       - `window.window_open`: Start epoch
///       - `window.window_close`: End epoch
///       - `window.midtime()`: Midpoint epoch
///       - `window.duration()`: Duration in seconds
#[pyclass(module = "brahe._brahe", subclass)]
#[pyo3(name = "AccessPropertyComputer")]
pub struct PyAccessPropertyComputer {
    // No internal state - subclasses will override methods
}

#[pymethods]
impl PyAccessPropertyComputer {
    #[new]
    #[pyo3(signature = (*_args, **_kwargs))]
    fn new(_args: &Bound<'_, PyTuple>, _kwargs: Option<&Bound<'_, PyDict>>) -> Self {
        PyAccessPropertyComputer {}
    }

    /// Return sampling configuration for this property computer.
    ///
    /// Override this method to specify how you want the satellite states to be
    /// sampled during the access window.
    ///
    /// Returns:
    ///     SamplingConfig: The sampling configuration
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     class MyComputer(bh.AccessPropertyComputer):
    ///         def sampling_config(self) -> bh.SamplingConfig:
    ///             return bh.SamplingConfig.midpoint()
    ///     ```
    fn sampling_config(&self) -> PyResult<PySamplingConfig> {
        Err(exceptions::PyNotImplementedError::new_err(
            "Subclasses must implement sampling_config() method",
        ))
    }

    /// Compute custom properties for an access window.
    ///
    /// Override this method in your subclass to implement custom property calculations.
    ///
    /// Args:
    ///     window (AccessWindow): Access window with timing information
    ///     sample_epochs (ndarray): Sample epochs in MJD (Modified Julian Date)
    ///     sample_states_ecef (ndarray): Satellite states in ECEF (N x 6) [x,y,z,vx,vy,vz] (meters, m/s)
    ///     location_ecef (ndarray or list): Location position in ECEF [x,y,z] (meters)
    ///     location_geodetic (ndarray or list): Location geodetic coordinates [lon,lat,alt] (radians, meters)
    ///
    /// Returns:
    ///     dict: Dictionary mapping property names (str) to values (scalar, list, dict, etc.)
    #[allow(unused_variables)]
    fn compute(
        &self,
        window: &PyAccessWindow,
        sample_epochs: PyReadonlyArray1<f64>,
        sample_states_ecef: PyReadonlyArray2<f64>,
        location_ecef: &Bound<'_, PyAny>,
        location_geodetic: &Bound<'_, PyAny>,
    ) -> PyResult<Py<PyDict>> {
        Err(exceptions::PyNotImplementedError::new_err(
            "Subclasses must implement compute() method",
        ))
    }

    /// Return list of property names this computer will produce.
    ///
    /// Override this method to return the list of property names that your
    /// compute() method will include in its returned dictionary.
    ///
    /// Returns:
    ///     list[str]: List of property names
    fn property_names(&self) -> PyResult<Vec<String>> {
        Err(exceptions::PyNotImplementedError::new_err(
            "Subclasses must implement property_names() method",
        ))
    }
}

// ================================
// Property Computer Holder
// ================================

/// Enum to hold either a native Rust property computer or a Python-wrapped one.
/// This allows built-in property computers to execute purely in Rust without
/// Python round-trip overhead, while custom Python property computers use the wrapper.
enum PropertyComputerHolder {
    /// Native Rust property computer (built-in types like DopplerComputer)
    RustNative(Box<dyn AccessPropertyComputer>),
    /// Python-defined property computer wrapped for Rust trait system
    PythonWrapper(RustAccessPropertyComputerWrapper),
}

impl AccessPropertyComputer for PropertyComputerHolder {
    fn sampling_config(&self) -> SamplingConfig {
        match self {
            PropertyComputerHolder::RustNative(computer) => computer.sampling_config(),
            PropertyComputerHolder::PythonWrapper(wrapper) => wrapper.sampling_config(),
        }
    }

    fn compute(
        &self,
        window: &AccessWindow,
        sample_epochs: &[f64],
        sample_states_ecef: &[nalgebra::SVector<f64, 6>],
        location_ecef: &nalgebra::Vector3<f64>,
        location_geodetic: &nalgebra::Vector3<f64>,
    ) -> Result<HashMap<String, PropertyValue>, RustBraheError> {
        match self {
            PropertyComputerHolder::RustNative(computer) => {
                computer.compute(window, sample_epochs, sample_states_ecef, location_ecef, location_geodetic)
            }
            PropertyComputerHolder::PythonWrapper(wrapper) => {
                wrapper.compute(window, sample_epochs, sample_states_ecef, location_ecef, location_geodetic)
            }
        }
    }

    fn property_names(&self) -> Vec<String> {
        match self {
            PropertyComputerHolder::RustNative(computer) => computer.property_names(),
            PropertyComputerHolder::PythonWrapper(wrapper) => wrapper.property_names(),
        }
    }
}

// Internal wrapper that implements the Rust AccessPropertyComputer trait
// by calling Python methods
#[allow(dead_code)]
pub(crate) struct RustAccessPropertyComputerWrapper {
    py_computer: Py<PyAny>,
}

#[allow(dead_code)]
impl RustAccessPropertyComputerWrapper {
    pub fn new(py_computer: Py<PyAny>) -> Self {
        RustAccessPropertyComputerWrapper { py_computer }
    }
}

impl AccessPropertyComputer for RustAccessPropertyComputerWrapper {
    fn sampling_config(&self) -> SamplingConfig {
        Python::attach(|py| {
            let py_obj = self.py_computer.bind(py);
            py_obj
                .call_method0("sampling_config")
                .and_then(|result| {
                    let py_config: &Bound<'_, PyAny> = &result;
                    // Try to extract as PySamplingConfig
                    if let Ok(config) = py_config.extract::<PySamplingConfig>() {
                        Ok(config.config.clone())
                    } else {
                        Err(pyo3::PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                            "sampling_config() must return a SamplingConfig",
                        ))
                    }
                })
                .unwrap_or(SamplingConfig::Midpoint)
        })
    }

    fn compute(
        &self,
        window: &AccessWindow,
        sample_epochs: &[f64],
        sample_states_ecef: &[nalgebra::SVector<f64, 6>],
        location_ecef: &nalgebra::Vector3<f64>,
        location_geodetic: &nalgebra::Vector3<f64>,
    ) -> Result<HashMap<String, PropertyValue>, RustBraheError> {
        Python::attach(|py| {
            // Convert sample_epochs to numpy array (1D)
            let epochs_array = sample_epochs.to_pyarray(py).to_owned();

            // Convert sample_states_ecef to numpy array (N x 6)
            let states_array = numpy::PyArray2::from_vec2(
                py,
                &sample_states_ecef
                    .iter()
                    .map(|state| state.as_slice().to_vec())
                    .collect::<Vec<_>>(),
            )
            .map_err(|e| RustBraheError::Error(format!("Failed to create states array: {}", e)))?
            .to_owned();

            // Convert location_ecef to numpy array
            let loc_array = location_ecef.as_slice().to_pyarray(py).to_owned();

            // Convert location_geodetic to numpy array
            let loc_geodetic_array = location_geodetic.as_slice().to_pyarray(py).to_owned();

            // Create Python AccessWindow
            let py_window = Py::new(
                py,
                PyAccessWindow {
                    window: window.clone(),
                },
            )
            .map_err(|e| RustBraheError::Error(format!("Failed to create PyAccessWindow: {}", e)))?;

            // Call Python compute method
            let py_obj = self.py_computer.bind(py);
            let result_dict = py_obj
                .call_method1(
                    "compute",
                    (py_window, epochs_array, states_array, loc_array, loc_geodetic_array),
                )
                .map_err(|e| {
                    RustBraheError::Error(format!("Python compute() method failed: {}", e))
                })?;

            // Convert Python dict to Rust HashMap<String, PropertyValue>
            let dict: &Bound<'_, PyDict> = result_dict
                .cast()
                .map_err(|e| RustBraheError::Error(format!("compute() must return a dict: {}", e)))?;

            let mut props = HashMap::new();
            for (key, value) in dict.iter() {
                let key_str: String = key.extract().map_err(|e| {
                    RustBraheError::Error(format!("Property keys must be strings: {}", e))
                })?;

                // Convert Python value to PropertyValue
                let prop_value = python_value_to_property_value(&value)?;
                props.insert(key_str, prop_value);
            }

            Ok(props)
        })
    }

    fn property_names(&self) -> Vec<String> {
        Python::attach(|py| {
            let py_obj = self.py_computer.bind(py);
            py_obj
                .call_method0("property_names")
                .and_then(|result| result.extract())
                .unwrap_or_else(|_| Vec::new())
        })
    }
}

// Helper function to convert Python values to PropertyValue
#[allow(dead_code)]
fn python_value_to_property_value(value: &Bound<'_, PyAny>) -> Result<PropertyValue, RustBraheError> {
    // Try bool first (before int/float, since bool is a subclass of int in Python)
    if let Ok(b) = value.extract::<bool>() {
        return Ok(PropertyValue::Boolean(b));
    }

    // Try float/int
    if let Ok(f) = value.extract::<f64>() {
        return Ok(PropertyValue::Scalar(f));
    }

    // Try string
    if let Ok(s) = value.extract::<String>() {
        return Ok(PropertyValue::String(s));
    }

    // Try list/array
    if let Ok(vec) = value.extract::<Vec<f64>>() {
        return Ok(PropertyValue::Vector(vec));
    }

    // Try dict (could be TimeSeries or generic JSON)
    if let Ok(dict) = value.cast::<PyDict>() {
        // Check if it's a time series format
        let has_times = dict.contains("times").map_err(|e| {
            RustBraheError::Error(format!("Failed to check for 'times' key: {}", e))
        })?;
        let has_values = dict.contains("values").map_err(|e| {
            RustBraheError::Error(format!("Failed to check for 'values' key: {}", e))
        })?;

        if has_times && has_values {
            let times: Vec<f64> = dict
                .get_item("times")
                .map_err(|e| RustBraheError::Error(format!("Failed to get 'times': {}", e)))?
                .ok_or_else(|| RustBraheError::Error("Missing 'times' key".to_string()))?
                .extract()
                .map_err(|e| RustBraheError::Error(format!("Failed to extract 'times': {}", e)))?;
            let values: Vec<f64> = dict
                .get_item("values")
                .map_err(|e| RustBraheError::Error(format!("Failed to get 'values': {}", e)))?
                .ok_or_else(|| RustBraheError::Error("Missing 'values' key".to_string()))?
                .extract()
                .map_err(|e| RustBraheError::Error(format!("Failed to extract 'values': {}", e)))?;
            return Ok(PropertyValue::TimeSeries { times, values });
        }

        // Otherwise, convert to JSON
        let json_module = value.py().import("json").map_err(|e| {
            RustBraheError::Error(format!("Failed to import json module: {}", e))
        })?;
        let dumps = json_module.getattr("dumps").map_err(|e| {
            RustBraheError::Error(format!("Failed to get json.dumps: {}", e))
        })?;
        let json_str: String = dumps
            .call1((value,))
            .and_then(|s| s.extract::<String>())
            .map_err(|e| RustBraheError::Error(format!("Failed to serialize to JSON: {}", e)))?;

        let json_value: serde_json::Value = serde_json::from_str(&json_str)
            .map_err(|e| RustBraheError::ParseError(format!("Invalid JSON: {}", e)))?;

        return Ok(PropertyValue::Json(json_value));
    }

    // Fallback: try to convert to JSON
    Python::attach(|py| {
        let json_module = py
            .import("json")
            .map_err(|e| RustBraheError::Error(format!("Failed to import json: {}", e)))?;
        let dumps = json_module
            .getattr("dumps")
            .map_err(|e| RustBraheError::Error(format!("Failed to get json.dumps: {}", e)))?;
        let json_str: String = dumps
            .call1((value,))
            .and_then(|s| s.extract::<String>())
            .map_err(|e| RustBraheError::Error(format!("Failed to serialize value: {}", e)))?;

        let json_value: serde_json::Value = serde_json::from_str(&json_str)
            .map_err(|e| RustBraheError::ParseError(format!("Invalid JSON: {}", e)))?;

        Ok(PropertyValue::Json(json_value))
    })
}

// ================================
// AccessConstraintComputer
// ================================

/// Base class for custom access constraint computers.
///
/// Subclass this class and implement the `evaluate` and `name` methods
/// to create custom constraint logic that can be applied to access computation.
///
/// The evaluate method is called at each time step during access search to determine
/// if the constraint is satisfied. Return True if the constraint is satisfied (access
/// is allowed), False otherwise.
///
/// Example:
///     ```python
///     import brahe as bh
///     import numpy as np
///
///     class NorthernHemisphereConstraint(bh.AccessConstraintComputer):
///         '''Only allows access when satellite is in northern hemisphere.'''
///
///         def evaluate(self, epoch: bh.Epoch, satellite_state_ecef: np.ndarray, location_ecef: np.ndarray) -> bool:
///             '''
///             Args:
///                 epoch (Epoch): Current evaluation time
///                 satellite_state_ecef (ndarray): Satellite state [x,y,z,vx,vy,vz] in ECEF (m, m/s)
///                 location_ecef (ndarray or list): Location position [x,y,z] in ECEF (m)
///
///             Returns:
///                 bool: True if constraint is satisfied, False otherwise
///             '''
///             # Check if satellite Z-coordinate (ECEF) is positive (northern hemisphere)
///             return satellite_state_ecef[2] >= 0.0
///
///         def name(self) -> str:
///             '''Return name of this constraint.'''
///             return "NorthernHemisphereConstraint"
///
///     # Use with access computation
///     custom_constraint = NorthernHemisphereConstraint()
///     # Then combine with other constraints using ConstraintAll or ConstraintAny
///     ```
///
/// Notes:
///     - The `evaluate` method receives ECEF coordinates in SI units (meters, m/s)
///     - Return True to allow access, False to reject
///     - The constraint is checked at each time step during access search
///     - Custom constraints can be combined with built-in constraints using ConstraintAll/ConstraintAny
#[pyclass(module = "brahe._brahe", subclass)]
#[pyo3(name = "AccessConstraintComputer")]
pub struct PyAccessConstraintComputer {
    // No internal state - subclasses will override methods
}

#[pymethods]
impl PyAccessConstraintComputer {
    #[new]
    fn new() -> Self {
        PyAccessConstraintComputer {}
    }

    /// Evaluate whether the constraint is satisfied.
    ///
    /// Override this method in your subclass to implement custom constraint logic.
    ///
    /// Args:
    ///     epoch (Epoch): Current evaluation time
    ///     satellite_state_ecef (ndarray): Satellite state in ECEF [x,y,z,vx,vy,vz] (meters, m/s)
    ///     location_ecef (ndarray or list): Location position in ECEF [x,y,z] (meters)
    ///
    /// Returns:
    ///     bool: True if constraint is satisfied (access allowed), False otherwise
    #[allow(unused_variables)]
    fn evaluate(
        &self,
        epoch: &PyEpoch,
        satellite_state_ecef: PyReadonlyArray1<f64>,
        location_ecef: &Bound<'_, PyAny>,
    ) -> PyResult<bool> {
        Err(exceptions::PyNotImplementedError::new_err(
            "Subclasses must implement evaluate() method",
        ))
    }

    /// Return name of this constraint computer.
    ///
    /// Override this method to return a descriptive name for your constraint.
    ///
    /// Returns:
    ///     str: Constraint name
    fn name(&self) -> PyResult<String> {
        Err(exceptions::PyNotImplementedError::new_err(
            "Subclasses must implement name() method",
        ))
    }
}

#[allow(dead_code)]
pub(crate) struct RustAccessConstraintComputerWrapper {
    py_computer: Py<PyAny>,
}

#[allow(dead_code)]
impl RustAccessConstraintComputerWrapper {
    pub fn new(py_computer: Py<PyAny>) -> Self {
        RustAccessConstraintComputerWrapper { py_computer }
    }
}

impl AccessConstraintComputer for RustAccessConstraintComputerWrapper {
    fn evaluate(
        &self,
        epoch: &Epoch,
        sat_state_ecef: &nalgebra::Vector6<f64>,
        location_ecef: &nalgebra::Vector3<f64>,
    ) -> bool {
        Python::attach(|py| {
            // Convert to numpy arrays
            let sat_state_array = sat_state_ecef.as_slice().to_pyarray(py).to_owned();
            let loc_array = location_ecef.as_slice().to_pyarray(py).to_owned();

            // Create Python Epoch
            let py_epoch = Py::new(
                py,
                PyEpoch {
                    obj: *epoch,
                },
            );

            // If epoch creation failed, return false (constraint not satisfied)
            let py_epoch = match py_epoch {
                Ok(e) => e,
                Err(e) => {
                    eprintln!("Warning: Failed to create PyEpoch: {}", e);
                    return false;
                }
            };

            // Call Python evaluate method
            let py_obj = self.py_computer.bind(py);
            let result = py_obj
                .call_method1("evaluate", (py_epoch, sat_state_array, loc_array));

            // If call failed or didn't return bool, return false (constraint not satisfied)
            match result {
                Ok(val) => val.extract::<bool>().unwrap_or_else(|e| {
                    eprintln!("Warning: evaluate() must return bool: {}", e);
                    false
                }),
                Err(e) => {
                    eprintln!("Warning: Python evaluate() method failed: {}", e);
                    false
                }
            }
        })
    }

    fn name(&self) -> &str {
        // Return a static string - we can't return Python strings from this trait method
        "PythonConstraintComputer"
    }
}

// ================================
// Access Computation Functions
// ================================

/// Configuration for how access windows are subdivided.
///
/// Supports two modes: equal-count (split into N equal parts) and fixed-duration
/// (generate sub-windows with a specific duration at regular intervals).
///
/// Can be created using keyword constructor or named class methods:
///
/// Args:
///     count (Optional[int]): Number of equal subdivisions (EqualCount mode)
///     duration (Optional[float]): Duration of each sub-window in seconds (FixedDuration mode)
///     offset (float): Offset from parent window start in seconds (default: 0.0)
///     gap (float): Gap between sub-windows in seconds, negative for overlap (default: 0.0)
///     truncate_partial (bool): If True, truncate partial sub-windows; if False, drop them (default: False)
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Equal-count mode via keyword constructor
///     config = bh.SubdivisionConfig(count=4)
///
///     # Equal-count mode via named constructor
///     config = bh.SubdivisionConfig.equal_count(4)
///
///     # Fixed-duration mode via keyword constructor
///     config = bh.SubdivisionConfig(duration=30.0, offset=10.0, gap=5.0)
///
///     # Fixed-duration mode via named constructor
///     config = bh.SubdivisionConfig.fixed_duration(
///         duration=30.0, offset=10.0, gap=5.0, truncate_partial=False
///     )
///     ```
#[pyclass(module = "brahe._brahe", from_py_object)]
#[pyo3(name = "SubdivisionConfig")]
#[derive(Clone)]
pub struct PySubdivisionConfig {
    pub(crate) config: SubdivisionConfig,
}

#[pymethods]
impl PySubdivisionConfig {
    /// Create a SubdivisionConfig.
    ///
    /// Detects mode from which arguments are provided:
    /// - Provide `count` for EqualCount mode
    /// - Provide `duration` for FixedDuration mode
    ///
    /// Args:
    ///     count (Optional[int]): Number of equal subdivisions
    ///     duration (Optional[float]): Duration of each sub-window in seconds
    ///     offset (float): Offset from parent window start in seconds (default: 0.0)
    ///     gap (float): Gap between sub-windows in seconds (default: 0.0)
    ///     truncate_partial (bool): Truncate partial sub-windows (default: False)
    ///
    /// Returns:
    ///     SubdivisionConfig: The configured subdivision
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     config = bh.SubdivisionConfig(count=4)
    ///     config = bh.SubdivisionConfig(duration=30.0, gap=5.0)
    ///     ```
    #[new]
    #[pyo3(signature = (count=None, duration=None, offset=0.0, gap=0.0, truncate_partial=false))]
    fn new(
        count: Option<usize>,
        duration: Option<f64>,
        offset: f64,
        gap: f64,
        truncate_partial: bool,
    ) -> PyResult<Self> {
        match (count, duration) {
            (Some(n), None) => Ok(Self {
                config: SubdivisionConfig::equal_count(n)?,
            }),
            (None, Some(d)) => Ok(Self {
                config: SubdivisionConfig::fixed_duration(d, offset, gap, truncate_partial)?,
            }),
            (Some(_), Some(_)) => Err(exceptions::PyValueError::new_err(
                "Specify either count or duration, not both",
            )),
            (None, None) => Err(exceptions::PyValueError::new_err(
                "Must specify either count or duration",
            )),
        }
    }

    /// Create an equal-count subdivision configuration.
    ///
    /// Splits each access window into N equal-duration sub-windows.
    ///
    /// Args:
    ///     count (int): Number of equal subdivisions (must be >= 1)
    ///
    /// Returns:
    ///     SubdivisionConfig: Equal-count subdivision configuration
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     config = bh.SubdivisionConfig.equal_count(4)
    ///     ```
    #[staticmethod]
    #[pyo3(signature = (count,))]
    fn equal_count(count: usize) -> PyResult<Self> {
        Ok(Self {
            config: SubdivisionConfig::equal_count(count)?,
        })
    }

    /// Create a fixed-duration subdivision configuration.
    ///
    /// Generates sub-windows with a specific duration at regular intervals
    /// within each parent access window.
    ///
    /// Args:
    ///     duration (float): Duration of each sub-window in seconds (must be > 0.0)
    ///     offset (float): Offset from parent window start in seconds (default: 0.0)
    ///     gap (float): Gap between sub-windows in seconds, negative for overlap (default: 0.0)
    ///     truncate_partial (bool): If True, truncate partial sub-windows; if False, drop them (default: False)
    ///
    /// Returns:
    ///     SubdivisionConfig: Fixed-duration subdivision configuration
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     config = bh.SubdivisionConfig.fixed_duration(
    ///         duration=30.0, offset=10.0, gap=5.0, truncate_partial=False
    ///     )
    ///     ```
    #[staticmethod]
    #[pyo3(signature = (duration, offset=0.0, gap=0.0, truncate_partial=false))]
    fn fixed_duration(
        duration: f64,
        offset: f64,
        gap: f64,
        truncate_partial: bool,
    ) -> PyResult<Self> {
        Ok(Self {
            config: SubdivisionConfig::fixed_duration(duration, offset, gap, truncate_partial)?,
        })
    }

    /// Get the count (for EqualCount mode).
    ///
    /// Returns:
    ///     Optional[int]: Number of subdivisions, or None if FixedDuration mode
    #[getter]
    fn count(&self) -> Option<usize> {
        match self.config {
            SubdivisionConfig::EqualCount { count } => Some(count),
            _ => None,
        }
    }

    /// Get the duration (for FixedDuration mode).
    ///
    /// Returns:
    ///     Optional[float]: Sub-window duration in seconds, or None if EqualCount mode
    #[getter]
    fn duration(&self) -> Option<f64> {
        match self.config {
            SubdivisionConfig::FixedDuration { duration, .. } => Some(duration),
            _ => None,
        }
    }

    /// Get the offset (for FixedDuration mode).
    ///
    /// Returns:
    ///     Optional[float]: Offset from parent window start in seconds, or None if EqualCount mode
    #[getter]
    fn offset(&self) -> Option<f64> {
        match self.config {
            SubdivisionConfig::FixedDuration { offset, .. } => Some(offset),
            _ => None,
        }
    }

    /// Get the gap (for FixedDuration mode).
    ///
    /// Returns:
    ///     Optional[float]: Gap between sub-windows in seconds, or None if EqualCount mode
    #[getter]
    fn gap(&self) -> Option<f64> {
        match self.config {
            SubdivisionConfig::FixedDuration { gap, .. } => Some(gap),
            _ => None,
        }
    }

    /// Get the truncate_partial flag (for FixedDuration mode).
    ///
    /// Returns:
    ///     Optional[bool]: Truncate partial flag, or None if EqualCount mode
    #[getter]
    fn truncate_partial(&self) -> Option<bool> {
        match self.config {
            SubdivisionConfig::FixedDuration {
                truncate_partial, ..
            } => Some(truncate_partial),
            _ => None,
        }
    }

    fn __repr__(&self) -> String {
        match self.config {
            SubdivisionConfig::EqualCount { count } => {
                format!("SubdivisionConfig.equal_count({})", count)
            }
            SubdivisionConfig::FixedDuration {
                duration,
                offset,
                gap,
                truncate_partial,
            } => {
                format!(
                    "SubdivisionConfig.fixed_duration(duration={}, offset={}, gap={}, truncate_partial={})",
                    duration,
                    offset,
                    gap,
                    if truncate_partial { "True" } else { "False" }
                )
            }
        }
    }
}

/// Configuration for access search grid parameters.
///
/// Controls the time step, adaptive stepping, boundary refinement tolerance,
/// and optional subdivision behavior for access window finding.
///
/// Args:
///     initial_time_step (float): Initial time step in seconds for grid search (default: 60.0)
///     adaptive_step (bool): Enable adaptive stepping after first access (default: False)
///     adaptive_fraction (float): Fraction of orbital period to use for adaptive step (default: 0.75)
///     parallel (bool): Enable parallel computation (default: True)
///     num_threads (Optional[int]): Number of threads for parallel computation (default: None)
///     time_tolerance (float): Boundary refinement tolerance in seconds (default: 0.001)
///     subdivisions (Optional[SubdivisionConfig]): Subdivision configuration per window (default: None)
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Create a config with custom parameters
///     config = bh.AccessSearchConfig(
///         initial_time_step=30.0,
///         adaptive_step=True,
///         adaptive_fraction=0.5
///     )
///
///     # Use config with location_accesses
///     windows = bh.location_accesses(
///         station, prop, search_start, search_end,
///         constraint, config=config
///     )
///
///     # Subdivide each access window into 4 equal-time sub-windows
///     config = bh.AccessSearchConfig(
///         subdivisions=bh.SubdivisionConfig.equal_count(4),
///         time_tolerance=0.01
///     )
///     sub_windows = bh.location_accesses(
///         station, prop, search_start, search_end,
///         constraint, config=config
///     )
///
///     # Fixed-duration sub-windows
///     config = bh.AccessSearchConfig(
///         subdivisions=bh.SubdivisionConfig.fixed_duration(30.0, gap=5.0)
///     )
///     ```
#[pyclass(module = "brahe._brahe", from_py_object)]
#[pyo3(name = "AccessSearchConfig")]
#[derive(Clone)]
pub struct PyAccessSearchConfig {
    pub(crate) config: AccessSearchConfig,
}

#[pymethods]
impl PyAccessSearchConfig {
    #[new]
    #[pyo3(signature = (initial_time_step=60.0, adaptive_step=false, adaptive_fraction=0.75, parallel=true, num_threads=None, time_tolerance=0.001, subdivisions=None))]
    fn new(
        initial_time_step: f64,
        adaptive_step: bool,
        adaptive_fraction: f64,
        parallel: bool,
        num_threads: Option<usize>,
        time_tolerance: f64,
        subdivisions: Option<PySubdivisionConfig>,
    ) -> Self {
        Self {
            config: AccessSearchConfig {
                initial_time_step,
                adaptive_step,
                adaptive_fraction,
                parallel,
                num_threads,
                time_tolerance,
                subdivisions: subdivisions.map(|s| s.config),
            },
        }
    }

    /// Get the initial time step in seconds.
    ///
    /// Returns:
    ///     float: Initial time step
    #[getter]
    fn initial_time_step(&self) -> f64 {
        self.config.initial_time_step
    }

    /// Set the initial time step in seconds.
    ///
    /// Args:
    ///     value (float): New initial time step
    #[setter]
    fn set_initial_time_step(&mut self, value: f64) {
        self.config.initial_time_step = value;
    }

    /// Get whether adaptive stepping is enabled.
    ///
    /// Returns:
    ///     bool: Adaptive stepping flag
    #[getter]
    fn adaptive_step(&self) -> PyResult<bool> {
        Ok(self.config.adaptive_step)
    }

    /// Set whether adaptive stepping is enabled.
    ///
    /// Args:
    ///     value (bool): Enable/disable adaptive stepping
    #[setter]
    fn set_adaptive_step(&mut self, value: bool) {
        self.config.adaptive_step = value;
    }

    /// Get the adaptive fraction (fraction of orbital period).
    ///
    /// Returns:
    ///     float: Adaptive fraction
    #[getter]
    fn adaptive_fraction(&self) -> f64 {
        self.config.adaptive_fraction
    }

    /// Set the adaptive fraction (fraction of orbital period).
    ///
    /// Args:
    ///     value (float): New adaptive fraction
    #[setter]
    fn set_adaptive_fraction(&mut self, value: f64) {
        self.config.adaptive_fraction = value;
    }

    /// Get whether parallel computation is enabled.
    ///
    /// Returns:
    ///     bool: Parallel computation flag (default: True)
    #[getter]
    fn parallel(&self) -> PyResult<bool> {
        Ok(self.config.parallel)
    }

    /// Set whether parallel computation is enabled.
    ///
    /// Args:
    ///     value (bool): Enable/disable parallel computation
    #[setter]
    fn set_parallel(&mut self, value: bool) {
        self.config.parallel = value;
    }

    /// Get the number of threads for parallel computation.
    ///
    /// Returns:
    ///     Optional[int]: Number of threads, or None to use global setting
    #[getter]
    fn num_threads(&self) -> Option<usize> {
        self.config.num_threads
    }

    /// Set the number of threads for parallel computation.
    ///
    /// Args:
    ///     value (Optional[int]): Number of threads, or None to use global setting
    #[setter]
    fn set_num_threads(&mut self, value: Option<usize>) {
        self.config.num_threads = value;
    }

    /// Get the boundary refinement tolerance in seconds.
    ///
    /// Returns:
    ///     float: Time tolerance in seconds
    #[getter]
    fn time_tolerance(&self) -> f64 {
        self.config.time_tolerance
    }

    /// Set the boundary refinement tolerance in seconds.
    ///
    /// Args:
    ///     value (float): New time tolerance in seconds
    #[setter]
    fn set_time_tolerance(&mut self, value: f64) {
        self.config.time_tolerance = value;
    }

    /// Get the subdivision configuration per access window.
    ///
    /// Returns:
    ///     Optional[SubdivisionConfig]: Subdivision configuration, or None for no subdivision
    #[getter]
    fn subdivisions(&self) -> Option<PySubdivisionConfig> {
        self.config
            .subdivisions
            .map(|config| PySubdivisionConfig { config })
    }

    /// Set the subdivision configuration per access window.
    ///
    /// Args:
    ///     value (Optional[SubdivisionConfig]): Subdivision configuration, or None for no subdivision
    #[setter]
    fn set_subdivisions(&mut self, value: Option<PySubdivisionConfig>) {
        self.config.subdivisions = value.map(|s| s.config);
    }

    fn __repr__(&self) -> String {
        let sub_repr = match &self.config.subdivisions {
            Some(s) => {
                let py_sub = PySubdivisionConfig { config: *s };
                py_sub.__repr__()
            }
            None => "None".to_string(),
        };
        format!(
            "AccessSearchConfig(initial_time_step={}, adaptive_step={}, adaptive_fraction={}, parallel={}, num_threads={:?}, time_tolerance={}, subdivisions={})",
            self.config.initial_time_step, self.config.adaptive_step, self.config.adaptive_fraction, self.config.parallel, self.config.num_threads, self.config.time_tolerance, sub_repr
        )
    }
}

/// Process property computers from Python objects to Rust holders.
///
/// This helper function extracts property computers from Python objects and wraps them
/// in the appropriate Rust holder type. Built-in property computers (Doppler, Range, RangeRate)
/// are extracted directly for zero-overhead execution, while custom Python-defined
/// computers are wrapped in the Python-Rust bridge.
fn process_property_computers(
    property_computers: Option<Vec<Py<PyAny>>>,
) -> Vec<PropertyComputerHolder> {
    if let Some(computers) = property_computers {
        computers
            .into_iter()
            .map(|py_computer| {
                Python::attach(|py| {
                    let obj = py_computer.bind(py);
                    if let Ok(doppler) = obj.cast::<PyDopplerComputer>() {
                        PropertyComputerHolder::RustNative(Box::new(
                            doppler.borrow().computer.clone(),
                        ))
                    } else if let Ok(range) = obj.cast::<PyRangeComputer>() {
                        PropertyComputerHolder::RustNative(Box::new(range.borrow().computer.clone()))
                    } else if let Ok(range_rate) = obj.cast::<PyRangeRateComputer>() {
                        PropertyComputerHolder::RustNative(Box::new(
                            range_rate.borrow().computer.clone(),
                        ))
                    } else {
                        PropertyComputerHolder::PythonWrapper(
                            RustAccessPropertyComputerWrapper::new(py_computer),
                        )
                    }
                })
            })
            .collect()
    } else {
        Vec::new()
    }
}

/// Compute access windows for locations and satellites.
///
/// This function accepts either single items or lists for both locations and propagators,
/// automatically handling all combinations. All location-satellite pairs are computed
/// and results are returned sorted by window start time.
///
/// Args:
///     locations (PointLocation | PolygonLocation | Sequence[PointLocation | PolygonLocation]):
///         Single location or list of locations
///     propagators (SGPPropagator | KeplerianPropagator | Sequence[SGPPropagator | KeplerianPropagator]):
///         Single propagator or list of propagators
///     search_start (Epoch): Start of search window
///     search_end (Epoch): End of search window
///     constraint (AccessConstraint): Access constraints to evaluate
///     property_computers (Optional[Sequence[AccessPropertyComputer]]): Optional property computers
///     config (Optional[AccessSearchConfig]): Search configuration (time step, tolerance, subdivisions, etc.)
///
/// Returns:
///     List[AccessWindow]: List of access windows sorted by start time
///
/// Example:
///     ```python
///     import brahe as bh
///     import numpy as np
///
///     # Create a ground station
///     station = bh.PointLocation(-75.0, 40.0, 0.0)  # Philadelphia
///
///     # Create satellite propagators
///     epoch = bh.Epoch(2024, 1, 1, 0, 0, 0.0)
///     oe = np.array([bh.R_EARTH + 500e3, 0.01, 97.8, 15.0, 30.0, 45.0])
///     state = bh.state_koe_to_eci(oe, bh.AngleFormat.DEGREES)
///     prop1 = bh.KeplerianPropagator(epoch, state)
///
///     # Define access constraints
///     constraint = bh.ElevationConstraint(10.0)  # 10 degree minimum elevation
///
///     # Single location, single propagator
///     search_end = epoch + 86400.0  # 1 day
///     windows = bh.location_accesses(station, prop1, epoch, search_end, constraint)
///
///     # Single location, multiple propagators
///     prop2 = bh.KeplerianPropagator(epoch, state)  # Different satellite
///     windows = bh.location_accesses(station, [prop1, prop2], epoch, search_end, constraint)
///
///     # Multiple locations, single propagator
///     station2 = bh.PointLocation(-122.0, 37.0, 0.0)  # San Francisco
///     windows = bh.location_accesses([station, station2], prop1, epoch, search_end, constraint)
///
///     # Multiple locations, multiple propagators
///     windows = bh.location_accesses([station, station2], [prop1, prop2], epoch, search_end, constraint)
///
///     # Custom search configuration with time tolerance and subdivisions
///     config = bh.AccessSearchConfig(initial_time_step=30.0, adaptive_step=True, time_tolerance=0.01)
///     windows = bh.location_accesses(station, prop1, epoch, search_end, constraint, config=config)
///     ```
#[pyfunction(name = "location_accesses")]
#[pyo3(signature = (locations, propagators, search_start, search_end, constraint, property_computers=None, config=None))]
#[allow(clippy::too_many_arguments)]
fn py_location_accesses(
    py: Python,
    locations: &Bound<'_, PyAny>,
    propagators: &Bound<'_, PyAny>,
    search_start: &PyEpoch,
    search_end: &PyEpoch,
    constraint: &Bound<'_, PyAny>,
    property_computers: Option<Vec<Py<PyAny>>>,
    config: Option<&PyAccessSearchConfig>,
) -> PyResult<Vec<PyAccessWindow>> {
    // Use provided config or create default
    let search_config = config.map(|c| c.config).unwrap_or_default();

    // Extract constraint as trait object
    let constraint_trait: &dyn AccessConstraint = if let Ok(c) = constraint.cast::<PyElevationConstraint>() {
        &c.borrow().constraint
    } else if let Ok(c) = constraint.cast::<PyOffNadirConstraint>() {
        &c.borrow().constraint
    } else if let Ok(c) = constraint.cast::<PyLocalTimeConstraint>() {
        &c.borrow().constraint
    } else if let Ok(c) = constraint.cast::<PyLookDirectionConstraint>() {
        &c.borrow().constraint
    } else if let Ok(c) = constraint.cast::<PyAscDscConstraint>() {
        &c.borrow().constraint
    } else if let Ok(c) = constraint.cast::<PyElevationMaskConstraint>() {
        &c.borrow().constraint
    } else if let Ok(c) = constraint.cast::<PyConstraintAll>() {
        &c.borrow().composite
    } else if let Ok(c) = constraint.cast::<PyConstraintAny>() {
        &c.borrow().composite
    } else if let Ok(c) = constraint.cast::<PyConstraintNot>() {
        &c.borrow().composite
    } else {
        return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
            "constraint must be an AccessConstraint type"
        ));
    };

    // Process locations - check if it's a list or single item
    let loc_is_list = locations.is_instance_of::<PyList>();

    // Process propagators - check if it's a list or single item
    let prop_is_list = propagators.is_instance_of::<PyList>();

    // Extract locations as vectors of references
    enum LocationVec {
        Point(Vec<PointLocation>),
        Polygon(Vec<PolygonLocation>),
    }

    let locations_vec = if loc_is_list {
        let list = locations.cast::<PyList>()?;
        let mut point_locs = Vec::new();
        let mut polygon_locs = Vec::new();
        let mut is_point = true;

        for item in list.iter() {
            if let Ok(loc) = item.cast::<PyPointLocation>() {
                point_locs.push(loc.borrow().location.clone());
            } else if let Ok(loc) = item.cast::<PyPolygonLocation>() {
                polygon_locs.push(loc.borrow().location.clone());
                is_point = false;
            } else {
                return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                    "locations list must contain only PointLocation or PolygonLocation objects"
                ));
            }
        }

        if is_point {
            LocationVec::Point(point_locs)
        } else {
            LocationVec::Polygon(polygon_locs)
        }
    } else if let Ok(loc) = locations.cast::<PyPointLocation>() {
        LocationVec::Point(vec![loc.borrow().location.clone()])
    } else if let Ok(loc) = locations.cast::<PyPolygonLocation>() {
        LocationVec::Polygon(vec![loc.borrow().location.clone()])
    } else {
        return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
            "locations must be PointLocation, PolygonLocation, or a list of these types"
        ));
    };

    // Check for NumericalOrbitPropagator first (cannot be cloned, so handled separately)
    // NumericalOrbitPropagator uses borrow guards with references instead of cloning
    let is_numerical = if prop_is_list {
        let list = propagators.cast::<PyList>()?;
        !list.is_empty() && list.get_item(0)?.is_instance_of::<PyNumericalOrbitPropagator>()
    } else {
        propagators.is_instance_of::<PyNumericalOrbitPropagator>()
    };

    // Check for OrbitTrajectory (handled like NumericalOrbitPropagator: borrow guards, no GIL release)
    let is_trajectory = if prop_is_list {
        let list = propagators.cast::<PyList>()?;
        !list.is_empty() && list.get_item(0)?.is_instance_of::<PyOrbitalTrajectory>()
    } else {
        propagators.is_instance_of::<PyOrbitalTrajectory>()
    };

    if is_trajectory {
        let borrow_guards: Vec<pyo3::PyRef<'_, PyOrbitalTrajectory>> = if prop_is_list {
            let list = propagators.cast::<PyList>()?;
            let mut guards = Vec::new();
            for item in list.iter() {
                if let Ok(traj) = item.cast::<PyOrbitalTrajectory>() {
                    guards.push(traj.borrow());
                } else {
                    return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                        "propagators list must contain only OrbitTrajectory objects (cannot mix types)"
                    ));
                }
            }
            guards
        } else {
            vec![propagators.cast::<PyOrbitalTrajectory>()?.borrow()]
        };

        let traj_refs: Vec<&trajectories::DOrbitTrajectory> =
            borrow_guards.iter().map(|g| &g.trajectory).collect();

        let rust_property_computers = process_property_computers(property_computers);

        let property_computer_refs: Vec<&dyn AccessPropertyComputer> = rust_property_computers
            .iter()
            .map(|c| c as &dyn AccessPropertyComputer)
            .collect();

        let property_computers_option = if property_computer_refs.is_empty() {
            None
        } else {
            Some(property_computer_refs.as_slice())
        };

        let windows = match &locations_vec {
            LocationVec::Point(locs) => location_accesses(
                locs,
                traj_refs.as_slice(),
                search_start.obj,
                search_end.obj,
                constraint_trait,
                property_computers_option,
                Some(&search_config),
            ),
            LocationVec::Polygon(locs) => location_accesses(
                locs,
                traj_refs.as_slice(),
                search_start.obj,
                search_end.obj,
                constraint_trait,
                property_computers_option,
                Some(&search_config),
            ),
        }?;

        return Ok(windows.into_iter().map(|w| PyAccessWindow { window: w }).collect());
    }

    if is_numerical {
        // Handle NumericalOrbitPropagator separately using borrow guards
        // (DNumericalOrbitPropagator doesn't implement Clone due to Box<dyn DIntegrator>)
        let borrow_guards: Vec<pyo3::PyRef<'_, PyNumericalOrbitPropagator>> = if prop_is_list {
            let list = propagators.cast::<PyList>()?;
            let mut guards = Vec::new();
            for item in list.iter() {
                if let Ok(prop) = item.cast::<PyNumericalOrbitPropagator>() {
                    guards.push(prop.borrow());
                } else {
                    return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                        "propagators list must contain only NumericalOrbitPropagator objects (cannot mix propagator types)"
                    ));
                }
            }
            guards
        } else {
            vec![propagators.cast::<PyNumericalOrbitPropagator>()?.borrow()]
        };

        // Create references from borrow guards
        let prop_refs: Vec<&propagators::DNumericalOrbitPropagator> =
            borrow_guards.iter().map(|g| &g.propagator).collect();

        // Process property computers using shared helper
        let rust_property_computers = process_property_computers(property_computers);

        let property_computer_refs: Vec<&dyn AccessPropertyComputer> = rust_property_computers
            .iter()
            .map(|c| c as &dyn AccessPropertyComputer)
            .collect();

        let property_computers_option = if property_computer_refs.is_empty() {
            None
        } else {
            Some(property_computer_refs.as_slice())
        };

        // Call location_accesses with the reference slice
        // NOTE: We do NOT release the GIL here (no py.allow_threads) because we hold
        // references into Python-owned NumericalOrbitPropagator objects. If another Python
        // thread mutated the propagator (e.g., via propagate_to()) while we're computing
        // access, we'd have a data race. The cloneable propagators path (SGP, Keplerian)
        // safely releases the GIL because it clones the propagators first.
        let windows = match &locations_vec {
            LocationVec::Point(locs) => location_accesses(
                locs,
                prop_refs.as_slice(),
                search_start.obj,
                search_end.obj,
                constraint_trait,
                property_computers_option,
                Some(&search_config),
            ),
            LocationVec::Polygon(locs) => location_accesses(
                locs,
                prop_refs.as_slice(),
                search_start.obj,
                search_end.obj,
                constraint_trait,
                property_computers_option,
                Some(&search_config),
            ),
        }?;

        return Ok(windows.into_iter().map(|w| PyAccessWindow { window: w }).collect());
    }

    // Extract propagators as vectors (for cloneable propagators: SGP, Keplerian)
    enum PropagatorVec {
        Sgp(Vec<crate::propagators::sgp_propagator::SGPPropagator>),
        Keplerian(Vec<crate::propagators::keplerian_propagator::KeplerianPropagator>),
    }

    let propagators_vec = if prop_is_list {
        let list = propagators.cast::<PyList>()?;
        let mut sgp_props = Vec::new();
        let mut kep_props = Vec::new();
        let mut is_sgp = true;

        for item in list.iter() {
            if let Ok(prop) = item.cast::<PySGPPropagator>() {
                sgp_props.push(prop.borrow().propagator.clone());
            } else if let Ok(prop) = item.cast::<PyKeplerianPropagator>() {
                kep_props.push(prop.borrow().propagator.clone());
                is_sgp = false;
            } else {
                return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                    "propagators list must contain only SGPPropagator or KeplerianPropagator objects"
                ));
            }
        }

        if is_sgp {
            PropagatorVec::Sgp(sgp_props)
        } else {
            PropagatorVec::Keplerian(kep_props)
        }
    } else if let Ok(prop) = propagators.cast::<PySGPPropagator>() {
        PropagatorVec::Sgp(vec![prop.borrow().propagator.clone()])
    } else if let Ok(prop) = propagators.cast::<PyKeplerianPropagator>() {
        PropagatorVec::Keplerian(vec![prop.borrow().propagator.clone()])
    } else {
        return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
            "propagators must be SGPPropagator, KeplerianPropagator, NumericalOrbitPropagator, OrbitTrajectory, or a list of these types"
        ));
    };

    // Process property computers using shared helper
    let rust_property_computers = process_property_computers(property_computers);

    // Create vector of trait object references
    let property_computer_refs: Vec<&dyn AccessPropertyComputer> = rust_property_computers
        .iter()
        .map(|c| c as &dyn AccessPropertyComputer)
        .collect();

    // Prepare optional slice
    let property_computers_option = if property_computer_refs.is_empty() {
        None
    } else {
        Some(property_computer_refs.as_slice())
    };

    // Call the Rust function with the extracted types
    // Release GIL to allow parallel execution and Python callbacks from threads
    let windows = py.detach(|| match (&locations_vec, &propagators_vec) {
        (LocationVec::Point(locs), PropagatorVec::Sgp(props)) => {
            location_accesses(
                locs,
                props,
                search_start.obj,
                search_end.obj,
                constraint_trait,
                property_computers_option,
                Some(&search_config),
            )
        }
        (LocationVec::Point(locs), PropagatorVec::Keplerian(props)) => {
            location_accesses(
                locs,
                props,
                search_start.obj,
                search_end.obj,
                constraint_trait,
                property_computers_option,
                Some(&search_config),
            )
        }
        (LocationVec::Polygon(locs), PropagatorVec::Sgp(props)) => {
            location_accesses(
                locs,
                props,
                search_start.obj,
                search_end.obj,
                constraint_trait,
                property_computers_option,
                Some(&search_config),
            )
        }
        (LocationVec::Polygon(locs), PropagatorVec::Keplerian(props)) => {
            location_accesses(
                locs,
                props,
                search_start.obj,
                search_end.obj,
                constraint_trait,
                property_computers_option,
                Some(&search_config),
            )
        }
    })?;

    // Convert to Python windows
    Ok(windows.into_iter().map(|w| PyAccessWindow { window: w }).collect())
}

// ================================
// Tessellation
// ================================

/// Configuration for the orbit geometry tessellator.
///
/// Controls tile dimensions, overlaps, and ascending/descending pass selection.
///
/// Args:
///     image_width (float): Cross-track tile width in meters (default: 5000)
///     image_length (float): Along-track tile length in meters (default: 5000)
///     crosstrack_overlap (float): Cross-track overlap in meters (default: 200)
///     alongtrack_overlap (float): Along-track overlap in meters (default: 200)
///     asc_dsc (AscDsc): Ascending/descending pass selection (default: Either)
///     min_image_length (float): Minimum tile length in meters (default: 5000)
///     max_image_length (float): Maximum tile length in meters (default: 5000)
///
/// Example:
///     ```python
///     import brahe as bh
///
///     config = bh.OrbitGeometryTessellatorConfig(
///         image_width=5000,
///         image_length=5000,
///         asc_dsc=bh.AscDsc.ASCENDING,
///     )
///     ```
#[pyclass(module = "brahe._brahe", from_py_object)]
#[pyo3(name = "OrbitGeometryTessellatorConfig")]
#[derive(Clone)]
pub struct PyOrbitGeometryTessellatorConfig {
    pub(crate) config: access::tessellation::OrbitGeometryTessellatorConfig,
}

#[pymethods]
impl PyOrbitGeometryTessellatorConfig {
    /// Create a new tessellation configuration.
    ///
    /// Args:
    ///     image_width (float): Cross-track tile width in meters
    ///     image_length (float): Along-track tile length in meters
    ///     crosstrack_overlap (float): Cross-track overlap in meters
    ///     alongtrack_overlap (float): Along-track overlap in meters
    ///     asc_dsc (AscDsc): Ascending/descending pass selection
    ///     min_image_length (float): Minimum tile length in meters
    ///     max_image_length (float): Maximum tile length in meters
    ///
    /// Returns:
    ///     OrbitGeometryTessellatorConfig: New configuration
    #[new]
    #[pyo3(signature = (
        image_width=5000.0,
        image_length=5000.0,
        crosstrack_overlap=200.0,
        alongtrack_overlap=200.0,
        asc_dsc=None,
        min_image_length=5000.0,
        max_image_length=5000.0,
    ))]
    fn new(
        image_width: f64,
        image_length: f64,
        crosstrack_overlap: f64,
        alongtrack_overlap: f64,
        asc_dsc: Option<PyAscDsc>,
        min_image_length: f64,
        max_image_length: f64,
    ) -> Self {
        let ad = asc_dsc.map(|a| a.value).unwrap_or(AscDsc::Either);
        Self {
            config: access::tessellation::OrbitGeometryTessellatorConfig {
                image_width,
                image_length,
                crosstrack_overlap,
                alongtrack_overlap,
                asc_dsc: ad,
                min_image_length,
                max_image_length,
            },
        }
    }

    /// Cross-track tile width in meters.
    ///
    /// Returns:
    ///     float: Tile width
    #[getter]
    fn image_width(&self) -> f64 {
        self.config.image_width
    }

    /// Along-track tile length in meters.
    ///
    /// Returns:
    ///     float: Tile length
    #[getter]
    fn image_length(&self) -> f64 {
        self.config.image_length
    }

    /// Cross-track overlap in meters.
    ///
    /// Returns:
    ///     float: Overlap
    #[getter]
    fn crosstrack_overlap(&self) -> f64 {
        self.config.crosstrack_overlap
    }

    /// Along-track overlap in meters.
    ///
    /// Returns:
    ///     float: Overlap
    #[getter]
    fn alongtrack_overlap(&self) -> f64 {
        self.config.alongtrack_overlap
    }

    /// Ascending/descending pass selection.
    ///
    /// Returns:
    ///     AscDsc: Pass selection
    #[getter]
    fn asc_dsc(&self) -> PyAscDsc {
        PyAscDsc {
            value: self.config.asc_dsc,
        }
    }

    /// Minimum tile length in meters.
    ///
    /// Returns:
    ///     float: Min tile length
    #[getter]
    fn min_image_length(&self) -> f64 {
        self.config.min_image_length
    }

    /// Maximum tile length in meters.
    ///
    /// Returns:
    ///     float: Max tile length
    #[getter]
    fn max_image_length(&self) -> f64 {
        self.config.max_image_length
    }

    fn __repr__(&self) -> String {
        format!(
            "OrbitGeometryTessellatorConfig(image_width={}, image_length={}, asc_dsc={:?})",
            self.config.image_width, self.config.image_length, self.config.asc_dsc,
        )
    }
}

/// Tessellator that uses orbital geometry to create rectangular tiles aligned
/// with satellite ground tracks.
///
/// Uses the satellite's orbital elements to compute along-track directions at
/// the target latitude, then tiles the area perpendicular and parallel to the
/// ground track. Each output tile is a PolygonLocation with metadata properties:
///
/// - ``tile_direction``: along-track unit ECEF vector [x, y, z]
/// - ``tile_width``: cross-track dimension (m)
/// - ``tile_length``: along-track dimension (m)
/// - ``tile_area``: width * length (m^2)
/// - ``tile_group_id``: UUID string shared by tiles in the same tiling direction
/// - ``spacecraft_ids``: list of spacecraft identifiers
///
/// Args:
///     propagator (SGPPropagator): Orbit propagator
///     epoch (Epoch): Reference epoch for the propagator
///     config (OrbitGeometryTessellatorConfig): Tessellation configuration
///     spacecraft_id (str): Optional spacecraft identifier for tile metadata
///
/// Example:
///     ```python
///     import brahe as bh
///
///     prop = bh.SGPPropagator(line1, line2)
///     config = bh.OrbitGeometryTessellatorConfig(
///         image_width=5000, image_length=5000
///     )
///     tess = bh.OrbitGeometryTessellator(prop, prop.epoch, config)
///     point = bh.PointLocation(10.0, 30.0, 0.0)
///     tiles = tess.tessellate_point(point)
///     ```
#[pyclass(module = "brahe._brahe")]
#[pyo3(name = "OrbitGeometryTessellator")]
pub struct PyOrbitGeometryTessellator {
    tessellator: access::tessellation::OrbitGeometryTessellator,
}

#[pymethods]
impl PyOrbitGeometryTessellator {
    /// Create a new orbit geometry tessellator.
    ///
    /// Args:
    ///     propagator (SGPPropagator): Orbit propagator
    ///     epoch (Epoch): Reference epoch for the propagator
    ///     config (OrbitGeometryTessellatorConfig): Tessellation configuration
    ///     spacecraft_id (str): Optional spacecraft identifier
    ///
    /// Returns:
    ///     OrbitGeometryTessellator: New tessellator
    #[new]
    #[pyo3(signature = (propagator, epoch, config=None, spacecraft_id=None))]
    fn new(
        propagator: &PySGPPropagator,
        epoch: &PyEpoch,
        config: Option<&PyOrbitGeometryTessellatorConfig>,
        spacecraft_id: Option<String>,
    ) -> PyResult<Self> {
        let rust_config = config
            .map(|c| c.config.clone())
            .unwrap_or_default();

        // Clone the propagator for the tessellator
        let prop_clone = propagator.propagator.clone();

        Ok(Self {
            tessellator: access::tessellation::OrbitGeometryTessellator::new(
                Box::new(prop_clone),
                epoch.obj,
                rust_config,
                spacecraft_id,
            ),
        })
    }

    /// Tessellate a point location into rectangular tiles.
    ///
    /// Creates one tile per orbital pass direction (ascending, descending, or both)
    /// centered on the point. At high latitudes where ascending and descending
    /// directions converge, redundant tiles may be automatically merged.
    ///
    /// Args:
    ///     point (PointLocation): Point to tessellate
    ///
    /// Returns:
    ///     list[PolygonLocation]: Tessellated tiles with metadata properties
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///
    ///     point = bh.PointLocation(10.0, 30.0, 0.0)
    ///     tiles = tessellator.tessellate_point(point)
    ///     for tile in tiles:
    ///         print(tile.properties)
    ///     ```
    fn tessellate_point(&self, point: &PyPointLocation) -> PyResult<Vec<PyPolygonLocation>> {
        let tiles = self
            .tessellator
            .tessellate(&point.location)
            .map_err(|e| BraheError::new_err(e.to_string()))?;

        Ok(tiles
            .into_iter()
            .map(|t| PyPolygonLocation { location: t })
            .collect())
    }

    /// Tessellate a polygon location into rectangular tiles.
    ///
    /// Divides the polygon into cross-track strips aligned with satellite ground
    /// tracks, then subdivides each strip along-track into tiles. Handles concave
    /// polygons by detecting gaps in the along-track direction.
    ///
    /// Args:
    ///     polygon (PolygonLocation): Polygon to tessellate
    ///
    /// Returns:
    ///     list[PolygonLocation]: Tessellated tiles with metadata properties
    ///
    /// Example:
    ///     ```python
    ///     import brahe as bh
    ///     import numpy as np
    ///
    ///     vertices = np.array([
    ///         [10.0, 30.0, 0.0],
    ///         [10.1, 30.0, 0.0],
    ///         [10.1, 30.1, 0.0],
    ///         [10.0, 30.1, 0.0],
    ///     ])
    ///     polygon = bh.PolygonLocation(vertices)
    ///     tiles = tessellator.tessellate_polygon(polygon)
    ///     ```
    fn tessellate_polygon(&self, polygon: &PyPolygonLocation) -> PyResult<Vec<PyPolygonLocation>> {
        let tiles = self
            .tessellator
            .tessellate(&polygon.location)
            .map_err(|e| BraheError::new_err(e.to_string()))?;

        Ok(tiles
            .into_iter()
            .map(|t| PyPolygonLocation { location: t })
            .collect())
    }

    /// Tessellate a location (point or polygon) into rectangular tiles.
    ///
    /// Dispatches to tessellate_point or tessellate_polygon based on input type.
    ///
    /// Args:
    ///     location (PointLocation | PolygonLocation): Location to tessellate
    ///
    /// Returns:
    ///     list[PolygonLocation]: Tessellated tiles with metadata properties
    fn tessellate(&self, location: &Bound<'_, PyAny>) -> PyResult<Vec<PyPolygonLocation>> {
        // Try to extract as PointLocation first
        if let Ok(point_ref) = location.cast::<PyPointLocation>() {
            let point = point_ref.borrow();
            let tiles = self
                .tessellator
                .tessellate(&point.location)
                .map_err(|e| BraheError::new_err(e.to_string()))?;
            return Ok(tiles
                .into_iter()
                .map(|t| PyPolygonLocation { location: t })
                .collect());
        }
        // Try PolygonLocation
        if let Ok(polygon_ref) = location.cast::<PyPolygonLocation>() {
            let polygon = polygon_ref.borrow();
            let tiles = self
                .tessellator
                .tessellate(&polygon.location)
                .map_err(|e| BraheError::new_err(e.to_string()))?;
            return Ok(tiles
                .into_iter()
                .map(|t| PyPolygonLocation { location: t })
                .collect());
        }
        Err(pyo3::exceptions::PyTypeError::new_err(
            "Expected PointLocation or PolygonLocation",
        ))
    }

    /// Get the tessellator configuration.
    ///
    /// Returns:
    ///     OrbitGeometryTessellatorConfig: Current configuration
    #[getter]
    fn config(&self) -> PyOrbitGeometryTessellatorConfig {
        PyOrbitGeometryTessellatorConfig {
            config: self.tessellator.config().clone(),
        }
    }

    /// Get the tessellator name.
    ///
    /// Returns:
    ///     str: Tessellator name
    fn name(&self) -> String {
        access::tessellation::Tessellator::name(&self.tessellator).to_string()
    }

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

/// Merge tessellation tiles from multiple spacecraft.
///
/// When multiple spacecraft can image the same area with similar ground-track
/// directions, tiles from one spacecraft can be merged onto another by adding
/// the alternate spacecraft's ID to the base tile's spacecraft_ids property.
///
/// Args:
///     tiles (list[PolygonLocation]): All tiles from all spacecraft
///     at_overlap (float): Along-track overlap in meters
///     ct_overlap (float): Cross-track overlap in meters
///     mergable_range_deg (float): Maximum angular difference in degrees for grouping directions
///
/// Returns:
///     list[PolygonLocation]: Reduced set of tiles with merged spacecraft_ids
///
/// Example:
///     ```python
///     import brahe as bh
///
///     # Tessellate with two spacecraft
///     tiles_sc1 = tess1.tessellate_point(point)
///     tiles_sc2 = tess2.tessellate_point(point)
///     all_tiles = tiles_sc1 + tiles_sc2
///
///     # Merge tiles with similar directions
///     merged = bh.tile_merge_orbit_geometry(all_tiles, 200.0, 200.0, 2.0)
///     ```
#[pyfunction]
#[pyo3(name = "tile_merge_orbit_geometry")]
#[pyo3(signature = (tiles, at_overlap=200.0, ct_overlap=200.0, mergable_range_deg=2.0))]
pub fn py_tile_merge_orbit_geometry(
    tiles: &Bound<'_, PyList>,
    at_overlap: f64,
    ct_overlap: f64,
    mergable_range_deg: f64,
) -> PyResult<Vec<PyPolygonLocation>> {
    let mut rust_tiles = Vec::new();
    for item in tiles.iter() {
        let poly_ref = item.cast::<PyPolygonLocation>()
            .map_err(|_| pyo3::exceptions::PyTypeError::new_err(
                "All items in tiles must be PolygonLocation"
            ))?;
        rust_tiles.push(poly_ref.borrow().location.clone());
    }

    let merged = access::tessellation::tile_merge_orbit_geometry(
        &rust_tiles,
        at_overlap,
        ct_overlap,
        mergable_range_deg,
    );

    Ok(merged
        .into_iter()
        .map(|t| PyPolygonLocation { location: t })
        .collect())
}