siderust 0.6.0

High-precision astronomy and satellite mechanics in Rust.
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Vallés Puig, Ramon

//! # Altitude Periods — Trait‑Based Dispatch Layer
//!
//! This module defines the [`AltitudePeriodsProvider`] trait and implementations
//! that normalise the "altitude periods" API across Sun, Moon, and fixed stars.
//!
//! ## Design
//!
//! The trait layer is the *dispatch* layer — no astronomical math lives
//! here.  Each `impl` delegates to the appropriate engine inside
//! [`calculus::solar`], [`calculus::lunar`], or [`calculus::stellar`].
//!
//! | Body type | Engine |
//! |-----------|--------|
//! | [`solar_system::Sun`] | [`calculus::solar::find_day_periods`] / [`calculus::solar::find_sun_range_periods`] |
//! | [`solar_system::Moon`] | [`calculus::lunar::find_moon_above_horizon`] / [`calculus::lunar::find_moon_altitude_range`] |
//! | [`Star`] | [`calculus::stellar::find_star_above_periods`] / [`calculus::stellar::find_star_range_periods`] |
//! | [`direction::ICRS`] | [`calculus::stellar::find_star_above_periods`] / [`calculus::stellar::find_star_range_periods`] |
//!
//! ## Quick Start
//!
//! ```rust
//! use siderust::bodies::Sun;
//! use siderust::calculus::altitude::{AltitudePeriodsProvider, AltitudeQuery};
//! use siderust::coordinates::centers::Geodetic;
//! use siderust::coordinates::frames::ECEF;
//! use siderust::coordinates::spherical::direction;
//! use siderust::time::{ModifiedJulianDate, MJD, Period};
//! use qtty::*;
//!
//! let site = Geodetic::<ECEF>::new(Degrees::new(0.0), Degrees::new(51.48), Meters::new(0.0));
//! let window = Period::new(ModifiedJulianDate::new(60000.0), ModifiedJulianDate::new(60001.0));
//!
//! let query = AltitudeQuery {
//!     observer: site,
//!     window,
//!     min_altitude: Degrees::new(-90.0),
//!     max_altitude: Degrees::new(0.0),
//! };
//!
//! // Same call shape for any body:
//! let sun_periods = Sun.altitude_periods(&query);
//! let star_periods = direction::ICRS::new(Degrees::new(101.287), Degrees::new(-16.716))
//!     .altitude_periods(&query);
//! ```

use super::types::AltitudeQuery;
use crate::bodies::solar_system;
use crate::bodies::Star;
use crate::coordinates::centers::Geodetic;
use crate::coordinates::frames::ECEF;
use crate::coordinates::spherical::direction;
use crate::time::{ModifiedJulianDate, Period, MJD};
use qtty::*;

// Imports for planet altitude support
use crate::calculus::horizontal;
use crate::coordinates::{cartesian, centers::Geocentric, frames};
use crate::time::JulianDate;

// ---------------------------------------------------------------------------
// Trait Definition
// ---------------------------------------------------------------------------

/// Unified interface for computing altitude periods of any celestial body.
///
/// Implementors delegate to the appropriate analytical/numerical engine in
/// the `calculus` layer.  The trait is intentionally small — one required
/// method plus convenience defaults.
///
/// Time scale note: all `ModifiedJulianDate` and `Period<MJD>` values are on
/// the canonical JD(TT) axis (`tempoch` semantics). Convert UTC instants with
/// `ModifiedJulianDate::from_utc(...)` before using this API.
pub trait AltitudePeriodsProvider {
    /// Returns all contiguous intervals inside `query.window` where the
    /// body's topocentric altitude is within
    /// `[query.min_altitude, query.max_altitude]`.
    ///
    /// `query.window` is interpreted on the TT axis (`Period<MJD>` with
    /// canonical `JD(TT)` semantics).
    ///
    /// The returned vector is sorted chronologically.  An empty vector
    /// means the body never enters the requested band during the window.
    fn altitude_periods(&self, query: &AltitudeQuery) -> Vec<Period<MJD>>;

    /// Convenience: intervals where altitude is **above** `threshold`.
    ///
    /// Default implementation calls [`altitude_periods`](Self::altitude_periods)
    /// with `max_altitude = 90°`.
    fn above_threshold(
        &self,
        observer: Geodetic<ECEF>,
        window: Period<MJD>,
        threshold: Degrees,
    ) -> Vec<Period<MJD>> {
        self.altitude_periods(&AltitudeQuery {
            observer,
            window,
            min_altitude: threshold,
            max_altitude: Degrees::new(90.0),
        })
    }

    /// Convenience: intervals where altitude is **below** `threshold`.
    ///
    /// Default implementation calls [`altitude_periods`](Self::altitude_periods)
    /// with `min_altitude = −90°`.
    fn below_threshold(
        &self,
        observer: Geodetic<ECEF>,
        window: Period<MJD>,
        threshold: Degrees,
    ) -> Vec<Period<MJD>> {
        self.altitude_periods(&AltitudeQuery {
            observer,
            window,
            min_altitude: Degrees::new(-90.0),
            max_altitude: threshold,
        })
    }

    /// Compute the altitude of this body at a single instant.
    ///
    /// Returns the topocentric altitude in radians.
    fn altitude_at(&self, observer: &Geodetic<ECEF>, mjd: ModifiedJulianDate) -> Radians;

    /// Hint for the scan step to use when searching for events.
    ///
    /// Returns `None` to use the default (10 minutes). Bodies with slower
    /// apparent motion (like the Moon) can return a larger step for efficiency.
    fn scan_step_hint(&self) -> Option<Days> {
        None
    }
}

// ---------------------------------------------------------------------------
// Free Function Entry Point
// ---------------------------------------------------------------------------

/// Generic entry point: compute altitude periods for any body that implements
/// [`AltitudePeriodsProvider`].
///
/// This is a thin wrapper around the trait method, provided for callers who
/// prefer a function‑style API.
///
/// # Example
/// ```rust
/// use siderust::calculus::altitude::{altitude_periods, AltitudeQuery};
/// use siderust::bodies::Sun;
/// use siderust::coordinates::centers::Geodetic;
/// use siderust::coordinates::frames::ECEF;
/// use siderust::time::{ModifiedJulianDate, MJD, Period};
/// use qtty::*;
///
/// let site = Geodetic::<ECEF>::new(Degrees::new(0.0), Degrees::new(51.48), Meters::new(0.0));
/// let window = Period::new(ModifiedJulianDate::new(60000.0), ModifiedJulianDate::new(60001.0));
/// let query = AltitudeQuery {
///     observer: site,
///     window,
///     min_altitude: Degrees::new(0.0),
///     max_altitude: Degrees::new(90.0),
/// };
/// let periods = altitude_periods(&Sun, &query);
/// ```
#[inline]
pub fn altitude_periods<B: AltitudePeriodsProvider>(
    body: &B,
    query: &AltitudeQuery,
) -> Vec<Period<MJD>> {
    body.altitude_periods(query)
}

// ---------------------------------------------------------------------------
// Implementations
// ---------------------------------------------------------------------------

/// **Sun** — delegates to [`calculus::solar`].
impl AltitudePeriodsProvider for solar_system::Sun {
    fn altitude_periods(&self, query: &AltitudeQuery) -> Vec<Period<MJD>> {
        if query.window.duration() <= Days::zero() {
            return Vec::new();
        }
        use crate::calculus::solar;

        // Fast path: full above query (max ≈ 90°)
        if query.max_altitude >= Degrees::new(89.99) {
            solar::find_day_periods(query.observer, query.window, query.min_altitude)
        } else if query.min_altitude <= Degrees::new(-89.99) {
            // Full below query
            solar::find_night_periods(query.observer, query.window, query.max_altitude)
        } else {
            solar::find_sun_range_periods(
                query.observer,
                query.window,
                (query.min_altitude, query.max_altitude),
            )
        }
    }

    fn altitude_at(&self, observer: &Geodetic<ECEF>, mjd: ModifiedJulianDate) -> Radians {
        crate::calculus::solar::sun_altitude_rad(mjd, observer)
    }
}

/// **Moon** — delegates to [`calculus::lunar`].
impl AltitudePeriodsProvider for solar_system::Moon {
    fn altitude_periods(&self, query: &AltitudeQuery) -> Vec<Period<MJD>> {
        if query.window.duration() <= Days::zero() {
            return Vec::new();
        }
        use crate::calculus::lunar;

        if query.max_altitude >= Degrees::new(89.99) {
            lunar::find_moon_above_horizon(query.observer, query.window, query.min_altitude)
        } else if query.min_altitude <= Degrees::new(-89.99) {
            lunar::find_moon_below_horizon(query.observer, query.window, query.max_altitude)
        } else {
            lunar::find_moon_altitude_range(
                query.observer,
                query.window,
                (query.min_altitude, query.max_altitude),
            )
        }
    }

    fn altitude_at(&self, observer: &Geodetic<ECEF>, mjd: ModifiedJulianDate) -> Radians {
        crate::calculus::lunar::moon_altitude_rad(mjd, observer)
    }

    fn scan_step_hint(&self) -> Option<Days> {
        // Moon moves slower, 2-hour steps are sufficient
        Some(Hours::new(2.0).to::<Day>())
    }
}

/// **Star** — extracts RA/Dec from the star's target, delegates to
/// [`calculus::stellar`].
impl AltitudePeriodsProvider for Star<'_> {
    fn altitude_periods(&self, query: &AltitudeQuery) -> Vec<Period<MJD>> {
        let dir = direction::ICRS::from(self);
        dir.altitude_periods(query)
    }

    fn altitude_at(&self, observer: &Geodetic<ECEF>, mjd: ModifiedJulianDate) -> Radians {
        let dir = direction::ICRS::from(self);
        dir.altitude_at(observer, mjd)
    }
}

/// **direction::ICRS** — the lightest path: raw RA/Dec → stellar engine.
impl AltitudePeriodsProvider for direction::ICRS {
    fn altitude_periods(&self, query: &AltitudeQuery) -> Vec<Period<MJD>> {
        if query.window.duration() <= Days::zero() {
            return Vec::new();
        }
        use crate::calculus::stellar;

        if query.max_altitude >= Degrees::new(89.99) {
            stellar::find_star_above_periods(
                self.ra(),
                self.dec(),
                query.observer,
                query.window,
                query.min_altitude,
            )
        } else if query.min_altitude <= Degrees::new(-89.99) {
            stellar::find_star_below_periods(
                self.ra(),
                self.dec(),
                query.observer,
                query.window,
                query.max_altitude,
            )
        } else {
            stellar::find_star_range_periods(
                self.ra(),
                self.dec(),
                query.observer,
                query.window,
                (query.min_altitude, query.max_altitude),
            )
        }
    }

    fn altitude_at(&self, observer: &Geodetic<ECEF>, mjd: ModifiedJulianDate) -> Radians {
        crate::calculus::stellar::fixed_star_altitude_rad(mjd, observer, self.ra(), self.dec())
    }
}

// ---------------------------------------------------------------------------
// Implementations: VSOP87 Planets (Mercury–Neptune)
// ---------------------------------------------------------------------------

use crate::calculus::math_core::intervals;
use crate::coordinates::transform::Transform;
use crate::time::complement_within;

/// Scan step for planet altitude threshold detection (2 hours in days).
///
/// Planets' apparent motion is dominated by Earth's rotation, so the same
/// 2‑hour scan step used for the Sun is adequate.
const PLANET_SCAN_STEP: Days = Quantity::<Hour>::new(2.0).to_const::<Day>();

/// Computes the topocentric altitude (in radians) of a VSOP87 planet at a
/// given instant, using the full VSOP87 → geocentric equatorial → topocentric
/// → horizontal pipeline.
fn vsop87_planet_altitude_rad<F>(
    vsop87e_fn: F,
    mjd: ModifiedJulianDate,
    site: &Geodetic<ECEF>,
) -> Radians
where
    F: Fn(
        JulianDate,
    ) -> cartesian::Position<
        crate::coordinates::centers::Barycentric,
        frames::EclipticMeanJ2000,
        AstronomicalUnit,
    >,
{
    let jd: JulianDate = mjd.into();
    // 1) VSOP87e → barycentric ecliptic J2000
    let bary_ecl = vsop87e_fn(jd);
    // 2) Frame rotation + center shift → geocentric equatorial J2000
    let geo_equ: cartesian::Position<Geocentric, frames::EquatorialMeanJ2000, AstronomicalUnit> =
        bary_ecl.transform(jd);
    // 3–4) Topocentric parallax + precession/nutation → true‑of‑date RA/Dec,
    //       then equatorial → horizontal
    let topo = horizontal::geocentric_j2000_to_apparent_topocentric(&geo_equ, *site, jd);
    let horiz = horizontal::equatorial_to_horizontal(&topo, *site, jd);
    horiz.alt().to::<Radian>()
}

/// Helper macro: implement [`AltitudePeriodsProvider`] for a VSOP87‑backed
/// planet unit type.  Delegates altitude computation through the
/// [`vsop87_planet_altitude_rad`] helper and uses [`intervals`] for
/// threshold/range queries.
macro_rules! impl_altitude_provider_vsop87 {
    ($($Planet:ident),+ $(,)?) => {
        $(
            impl AltitudePeriodsProvider for solar_system::$Planet {
                fn altitude_periods(&self, query: &AltitudeQuery) -> Vec<Period<MJD>> {
                    if query.window.duration() <= Days::zero() {
                        return Vec::new();
                    }
                    let f = |t: ModifiedJulianDate| -> Radians {
                        vsop87_planet_altitude_rad(
                            solar_system::$Planet::vsop87e, t, &query.observer,
                        )
                    };
                    if query.max_altitude >= Degrees::new(89.99) {
                        // Full "above" query
                        intervals::above_threshold_periods(
                            query.window,
                            PLANET_SCAN_STEP,
                            &f,
                            query.min_altitude.to::<Radian>(),
                        )
                    } else if query.min_altitude <= Degrees::new(-89.99) {
                        // Full "below" query — complement of above(max)
                        let above = intervals::above_threshold_periods(
                            query.window,
                            PLANET_SCAN_STEP,
                            &f,
                            query.max_altitude.to::<Radian>(),
                        );
                        complement_within(query.window, &above)
                    } else {
                        // Band [min, max] query
                        intervals::in_range_periods(
                            query.window,
                            PLANET_SCAN_STEP,
                            &f,
                            query.min_altitude.to::<Radian>(),
                            query.max_altitude.to::<Radian>(),
                        )
                    }
                }

                fn altitude_at(
                    &self,
                    observer: &Geodetic<ECEF>,
                    mjd: ModifiedJulianDate,
                ) -> Radians {
                    vsop87_planet_altitude_rad(
                        solar_system::$Planet::vsop87e, mjd, observer,
                    )
                }

                fn scan_step_hint(&self) -> Option<Days> {
                    Some(PLANET_SCAN_STEP)
                }
            }
        )+
    };
}

impl_altitude_provider_vsop87!(Mercury, Venus, Mars, Jupiter, Saturn, Uranus, Neptune);

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bodies::catalog;

    fn greenwich() -> Geodetic<ECEF> {
        Geodetic::<ECEF>::new(Degrees::new(0.0), Degrees::new(51.4769), Meters::new(0.0))
    }

    fn one_day_window() -> Period<MJD> {
        Period::new(
            ModifiedJulianDate::new(60000.0),
            ModifiedJulianDate::new(60001.0),
        )
    }

    fn one_week_window() -> Period<MJD> {
        Period::new(
            ModifiedJulianDate::new(60000.0),
            ModifiedJulianDate::new(60007.0),
        )
    }

    // --- Consistent API shape ---

    #[test]
    fn sun_above_horizon_via_trait() {
        let periods =
            solar_system::Sun.above_threshold(greenwich(), one_day_window(), Degrees::new(0.0));
        assert!(!periods.is_empty(), "Sun should be above horizon at 51°N");
        for p in &periods {
            assert!(p.duration_days() > 0.0);
            assert!(p.duration_days() < 1.0);
        }
    }

    #[test]
    fn moon_above_horizon_via_trait() {
        let periods =
            solar_system::Moon.above_threshold(greenwich(), one_week_window(), Degrees::new(0.0));
        assert!(
            !periods.is_empty(),
            "Moon should be above horizon at some point in a week"
        );
    }

    #[test]
    fn star_above_horizon_via_trait() {
        let sirius = &catalog::SIRIUS;
        let periods = sirius.above_threshold(greenwich(), one_day_window(), Degrees::new(0.0));
        // Sirius (Dec ≈ −16.7°) rises and sets at 51°N
        assert!(
            !periods.is_empty(),
            "Sirius should be above horizon for part of the day"
        );
    }

    #[test]
    fn icrs_direction_above_horizon_via_trait() {
        let sirius_dir = direction::ICRS::new(Degrees::new(101.287), Degrees::new(-16.716));
        let periods = sirius_dir.above_threshold(greenwich(), one_day_window(), Degrees::new(0.0));
        assert!(
            !periods.is_empty(),
            "direction::ICRS for Sirius should match Star result"
        );
    }

    #[test]
    fn star_and_icrs_direction_agree() {
        let sirius = &catalog::SIRIUS;
        let sirius_dir = direction::ICRS::from(sirius);

        let window = one_day_window();
        let observer = greenwich();

        let star_periods = sirius.above_threshold(observer, window, Degrees::new(0.0));
        let dir_periods = sirius_dir.above_threshold(observer, window, Degrees::new(0.0));

        assert_eq!(
            star_periods.len(),
            dir_periods.len(),
            "Star and direction::ICRS should produce the same number of periods"
        );
        for (sp, dp) in star_periods.iter().zip(dir_periods.iter()) {
            assert!(
                (sp.start - dp.start).abs() < Days::new(1e-6),
                "Period starts should match"
            );
            assert!(
                (sp.end - dp.end).abs() < Days::new(1e-6),
                "Period ends should match"
            );
        }
    }

    // --- Generic free function ---

    #[test]
    fn free_function_works_for_sun() {
        let query = AltitudeQuery {
            observer: greenwich(),
            window: one_day_window(),
            min_altitude: Degrees::new(0.0),
            max_altitude: Degrees::new(90.0),
        };
        let periods = altitude_periods(&solar_system::Sun, &query);
        assert!(!periods.is_empty());
    }

    #[test]
    fn free_function_works_for_icrs_direction() {
        let dir = direction::ICRS::new(Degrees::new(101.287), Degrees::new(-16.716));
        let query = AltitudeQuery {
            observer: greenwich(),
            window: one_day_window(),
            min_altitude: Degrees::new(0.0),
            max_altitude: Degrees::new(90.0),
        };
        let periods = altitude_periods(&dir, &query);
        assert!(!periods.is_empty());
    }

    // --- altitude_at single-point ---

    #[test]
    fn altitude_at_consistent_across_types() {
        let observer = greenwich();
        let mjd = ModifiedJulianDate::new(51544.5); // J2000 epoch in MJD

        let sun_alt = solar_system::Sun.altitude_at(&observer, mjd);
        assert!(sun_alt.abs() < std::f64::consts::FRAC_PI_2);

        let moon_alt = solar_system::Moon.altitude_at(&observer, mjd);
        assert!(moon_alt.abs() < std::f64::consts::FRAC_PI_2);

        let sirius_dir = direction::ICRS::new(Degrees::new(101.287), Degrees::new(-16.716));
        let star_alt = sirius_dir.altitude_at(&observer, mjd);
        assert!(star_alt.abs() < std::f64::consts::FRAC_PI_2);
    }

    // --- Edge cases ---

    #[test]
    fn full_sky_range_returns_full_window() {
        let query = AltitudeQuery {
            observer: greenwich(),
            window: one_day_window(),
            min_altitude: Degrees::new(-90.0),
            max_altitude: Degrees::new(90.0),
        };
        let periods = solar_system::Sun.altitude_periods(&query);
        // The sun's altitude is always in [-90, 90], so we should get the full window
        assert!(
            !periods.is_empty(),
            "Full sky range should return at least one period"
        );
        let total: f64 = periods.iter().map(|p| p.duration_days()).sum();
        assert!(
            (total - 1.0).abs() < 0.01,
            "Full sky range should span ~1 day, got {} days",
            total
        );
    }

    #[test]
    fn polaris_circumpolar_via_trait() {
        let polaris = &catalog::POLARIS;
        let periods = polaris.above_threshold(greenwich(), one_day_window(), Degrees::new(0.0));
        assert_eq!(
            periods.len(),
            1,
            "Polaris should be continuously above horizon at 51°N"
        );
        assert!(
            (periods[0].duration_days() - Days::new(1.0)).abs() < Days::new(0.01),
            "Polaris up-period should span the full day"
        );
    }

    #[test]
    fn polaris_never_below_minus90_via_trait() {
        let polaris = &catalog::POLARIS;
        // Polaris is circumpolar at 51°N — should never be below -90° (vacuous)
        let periods = polaris.below_threshold(greenwich(), one_day_window(), Degrees::new(-80.0));
        assert!(
            periods.is_empty(),
            "Polaris should never be below -80° at 51°N"
        );
    }

    #[test]
    fn empty_window_returns_empty() {
        let window = Period::new(
            ModifiedJulianDate::new(60000.0),
            ModifiedJulianDate::new(60000.0),
        );
        let query = AltitudeQuery {
            observer: greenwich(),
            window,
            min_altitude: Degrees::new(0.0),
            max_altitude: Degrees::new(90.0),
        };
        let periods = solar_system::Sun.altitude_periods(&query);
        assert!(periods.is_empty(), "Empty window should return no periods");
    }

    #[test]
    fn below_threshold_sun_night_via_trait() {
        let nights =
            solar_system::Sun.below_threshold(greenwich(), one_week_window(), Degrees::new(-18.0));
        assert!(!nights.is_empty(), "Should find astronomical night at 51°N");
    }

    #[test]
    fn altitude_range_twilight_via_trait() {
        let query = AltitudeQuery {
            observer: greenwich(),
            window: Period::new(
                ModifiedJulianDate::new(60000.0),
                ModifiedJulianDate::new(60002.0),
            ),
            min_altitude: Degrees::new(-18.0),
            max_altitude: Degrees::new(-12.0),
        };
        let bands = solar_system::Sun.altitude_periods(&query);
        assert!(
            bands.len() >= 2,
            "Should find at least 2 twilight bands in 2 days, found {}",
            bands.len()
        );
    }

    // --- Periods are sorted and non-overlapping ---

    #[test]
    fn periods_are_sorted_and_non_overlapping() {
        let sirius_dir = direction::ICRS::new(Degrees::new(101.287), Degrees::new(-16.716));
        let periods = sirius_dir.above_threshold(greenwich(), one_week_window(), Degrees::new(0.0));
        for w in periods.windows(2) {
            assert!(
                w[0].end <= w[1].start,
                "Periods should be non-overlapping and sorted: {:?} vs {:?}",
                w[0],
                w[1]
            );
        }
    }

    // --- Planet altitude ---

    #[test]
    fn mars_altitude_at_is_finite() {
        let alt = solar_system::Mars.altitude_at(&greenwich(), ModifiedJulianDate::new(60000.5));
        assert!(alt.is_finite());
        assert!(
            alt.abs() < Radians::new(std::f64::consts::FRAC_PI_2),
            "Mars altitude should be within ±90°"
        );
    }

    #[test]
    fn jupiter_above_horizon_via_trait() {
        let periods = solar_system::Jupiter.above_threshold(
            greenwich(),
            one_week_window(),
            Degrees::new(0.0),
        );
        assert!(
            !periods.is_empty(),
            "Jupiter should be above horizon at some point in a week at 51°N"
        );
    }

    #[test]
    fn planet_altitudes_are_realistic() {
        let observer = greenwich();
        let mjd = ModifiedJulianDate::new(60000.5);
        // All planets should return finite altitudes
        let mercury_alt = solar_system::Mercury.altitude_at(&observer, mjd);
        let venus_alt = solar_system::Venus.altitude_at(&observer, mjd);
        let mars_alt = solar_system::Mars.altitude_at(&observer, mjd);
        let saturn_alt = solar_system::Saturn.altitude_at(&observer, mjd);
        let uranus_alt = solar_system::Uranus.altitude_at(&observer, mjd);
        let neptune_alt = solar_system::Neptune.altitude_at(&observer, mjd);

        for (name, alt) in [
            ("Mercury", mercury_alt),
            ("Venus", venus_alt),
            ("Mars", mars_alt),
            ("Saturn", saturn_alt),
            ("Uranus", uranus_alt),
            ("Neptune", neptune_alt),
        ] {
            assert!(alt.is_finite(), "{name} altitude should be finite");
            assert!(
                alt.abs() < Radians::new(std::f64::consts::FRAC_PI_2),
                "{name} altitude should be within ±90°, got {alt}"
            );
        }
    }
}