solunatus 0.4.0

High-precision astronomical calculation library and CLI for sun/moon positions, rise/set times, and lunar phases
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
//! JSON output formatting.
//!
//! Provides structured JSON output for astronomical data including
//! positions, events, phases, and optional AI insights.

#[cfg(feature = "ai-insights")]
use crate::ai;
use crate::astro::*;
use crate::events;
use crate::time_sync;
use anyhow::Result;
use chrono::{DateTime, Datelike, Utc};
use chrono_tz::Tz;
use serde::Serialize;

/// Top-level JSON output structure for astronomical data.
///
/// Contains all calculated positions, events, phases, and optional AI insights.
#[derive(Serialize)]
pub struct JsonOutput {
    /// Geographic location information
    pub location: LocationData,
    /// Current date and time information
    pub datetime: DateTimeData,
    /// Solar position and events
    pub sun: SunData,
    /// Lunar position, events, and phase
    pub moon: MoonData,
    /// Lunar phases for current month
    pub lunar_phases: Vec<LunarPhaseData>,
    /// Optional AI-generated insights
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ai_insights: Option<AiInsightsData>,
}

/// Geographic location data for JSON output.
#[derive(Serialize)]
pub struct LocationData {
    /// Latitude in decimal degrees (WGS84)
    pub latitude: f64,
    /// Longitude in decimal degrees (WGS84)
    pub longitude: f64,
    /// IANA timezone identifier
    pub timezone: String,
    /// Optional city name
    pub city: Option<String>,
}

/// Date and time information for JSON output.
#[derive(Serialize)]
pub struct DateTimeData {
    /// Local time with timezone
    pub local: String,
    /// UTC time
    pub utc: String,
    /// Timezone offset (e.g., "+05:00")
    pub timezone_offset: String,
    /// NTP time synchronization status
    pub time_sync: TimeSyncData,
}

/// Solar position and events for JSON output.
#[derive(Serialize)]
pub struct SunData {
    /// Current sun position (altitude, azimuth)
    pub position: PositionData,
    /// Solar events (sunrise, sunset, twilight times)
    pub events: SunEvents,
}

/// Lunar position, events, and phase for JSON output.
#[derive(Serialize)]
pub struct MoonData {
    /// Current moon position (altitude, azimuth, distance, size)
    pub position: MoonPositionData,
    /// Lunar events (moonrise, moonset)
    pub events: MoonEvents,
    /// Current lunar phase details
    pub phase: PhaseData,
}

/// Celestial body position (sun/moon) for JSON output.
#[derive(Serialize)]
pub struct PositionData {
    /// Altitude in degrees (+ above horizon, - below)
    pub altitude: f64,
    /// Azimuth in degrees (0° = North, clockwise)
    pub azimuth: f64,
    /// Compass direction (e.g., "NE", "SW")
    pub azimuth_compass: String,
}

/// Lunar position with distance and angular size for JSON output.
#[derive(Serialize)]
pub struct MoonPositionData {
    /// Altitude in degrees (+ above horizon, - below)
    pub altitude: f64,
    /// Azimuth in degrees (0° = North, clockwise)
    pub azimuth: f64,
    /// Compass direction (e.g., "NE", "SW")
    pub azimuth_compass: String,
    /// Distance from Earth in kilometers
    pub distance_km: f64,
    /// Angular diameter in arcminutes
    pub angular_diameter_arcmin: f64,
}

/// Solar events for JSON output.
///
/// All times are formatted as "YYYY-MM-DD HH:MM:SS TZ".
/// Events are `None` if they don't occur on the given day (e.g., polar regions).
#[derive(Serialize)]
pub struct SunEvents {
    /// Sunrise time
    pub sunrise: Option<String>,
    /// Sunset time
    pub sunset: Option<String>,
    /// Solar noon (sun at highest altitude)
    pub solar_noon: Option<String>,
    /// Civil dawn (sun at -6° altitude)
    pub civil_dawn: Option<String>,
    /// Civil dusk (sun at -6° altitude)
    pub civil_dusk: Option<String>,
    /// Nautical dawn (sun at -12° altitude)
    pub nautical_dawn: Option<String>,
    /// Nautical dusk (sun at -12° altitude)
    pub nautical_dusk: Option<String>,
    /// Astronomical dawn (sun at -18° altitude)
    pub astronomical_dawn: Option<String>,
    /// Astronomical dusk (sun at -18° altitude)
    pub astronomical_dusk: Option<String>,
}

/// Lunar events for JSON output.
///
/// Times are formatted as "YYYY-MM-DD HH:MM:SS TZ".
/// Events are `None` if they don't occur on the given day.
#[derive(Serialize)]
pub struct MoonEvents {
    /// Moonrise time
    pub moonrise: Option<String>,
    /// Moonset time
    pub moonset: Option<String>,
}

/// Current lunar phase details for JSON output.
#[derive(Serialize)]
pub struct PhaseData {
    /// Phase name (e.g., "Full Moon", "Waxing Crescent")
    pub name: String,
    /// Emoji representation of phase
    pub emoji: String,
    /// Phase angle in degrees (0° = new, 180° = full)
    pub angle_degrees: f64,
    /// Illumination percentage (0-100)
    pub illumination_percent: f64,
}

/// Lunar phase event data for JSON output.
#[derive(Serialize)]
pub struct LunarPhaseData {
    /// Phase type: "new_moon", "first_quarter", "full_moon", "last_quarter"
    pub phase_type: String,
    /// UTC timestamp of phase event
    pub datetime: String,
}

/// NTP time synchronization status for JSON output.
#[derive(Serialize)]
pub struct TimeSyncData {
    /// NTP server source (e.g., "time.google.com (NTP)")
    pub source: String,
    /// Clock offset in seconds (system - NTP time)
    pub delta_seconds: Option<f64>,
    /// Human-readable offset (e.g., "+2.3s", "-150.0ms")
    pub offset_display: Option<String>,
    /// Status code: "ahead", "behind", "in_sync", "error", "unavailable"
    pub status: String,
    /// Error message if time sync failed
    pub error: Option<String>,
}

/// AI-generated insights for JSON output.
#[derive(Serialize)]
pub struct AiInsightsData {
    /// Ollama model used to generate insights
    pub model: String,
    /// Timestamp when insights were generated
    pub updated_at: String,
    /// Time elapsed since last update (e.g., "Updated 02:15 ago")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_elapsed: Option<String>,
    /// Generated insights text
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    /// Error message if insights generation failed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Generates JSON output for astronomical data (with AI insights support).
///
/// Creates a complete JSON document containing positions, events, phases,
/// time sync status, and optional AI-generated insights.
///
/// # Arguments
///
/// * `location` - Geographic location
/// * `timezone` - Timezone for event times
/// * `city_name` - Optional city name
/// * `dt` - Current date/time
/// * `timezone_name` - Timezone display name
/// * `time_sync_info` - NTP time sync status
/// * `ai_config` - AI configuration (if ai-insights feature enabled)
///
/// # Returns
///
/// A pretty-printed JSON string containing all astronomical data.
///
/// # Errors
///
/// Returns an error if JSON serialization fails.
#[cfg(feature = "ai-insights")]
pub fn generate_json_output(
    location: &Location,
    timezone: &Tz,
    city_name: Option<String>,
    dt: &DateTime<Tz>,
    timezone_name: &str,
    time_sync_info: &time_sync::TimeSyncInfo,
    ai_config: &ai::AiConfig,
) -> Result<String> {
    generate_json_output_impl(
        location,
        timezone,
        city_name,
        dt,
        timezone_name,
        time_sync_info,
        Some(ai_config),
    )
}

/// Generates JSON output for astronomical data (without AI insights).
///
/// Creates a complete JSON document containing positions, events, phases,
/// and time sync status.
///
/// # Arguments
///
/// * `location` - Geographic location
/// * `timezone` - Timezone for event times
/// * `city_name` - Optional city name
/// * `dt` - Current date/time
/// * `timezone_name` - Timezone display name
/// * `time_sync_info` - NTP time sync status
///
/// # Returns
///
/// A pretty-printed JSON string containing all astronomical data.
///
/// # Errors
///
/// Returns an error if JSON serialization fails.
#[cfg(not(feature = "ai-insights"))]
pub fn generate_json_output(
    location: &Location,
    timezone: &Tz,
    city_name: Option<String>,
    dt: &DateTime<Tz>,
    timezone_name: &str,
    time_sync_info: &time_sync::TimeSyncInfo,
) -> Result<String> {
    generate_json_output_impl(
        location,
        timezone,
        city_name,
        dt,
        timezone_name,
        time_sync_info,
        None,
    )
}

#[cfg(feature = "ai-insights")]
fn generate_json_output_impl(
    location: &Location,
    timezone: &Tz,
    city_name: Option<String>,
    dt: &DateTime<Tz>,
    timezone_name: &str,
    time_sync_info: &time_sync::TimeSyncInfo,
    ai_config: Option<&ai::AiConfig>,
) -> Result<String> {
    // Calculate sun position and events
    let sun_pos = sun::solar_position(location, dt);
    let sun_events = SunEvents {
        sunrise: sun::solar_event_time(location, dt, sun::SolarEvent::Sunrise)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        sunset: sun::solar_event_time(location, dt, sun::SolarEvent::Sunset)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        solar_noon: sun::solar_event_time(location, dt, sun::SolarEvent::SolarNoon)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        civil_dawn: sun::solar_event_time(location, dt, sun::SolarEvent::CivilDawn)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        civil_dusk: sun::solar_event_time(location, dt, sun::SolarEvent::CivilDusk)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        nautical_dawn: sun::solar_event_time(location, dt, sun::SolarEvent::NauticalDawn)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        nautical_dusk: sun::solar_event_time(location, dt, sun::SolarEvent::NauticalDusk)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        astronomical_dawn: sun::solar_event_time(location, dt, sun::SolarEvent::AstronomicalDawn)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        astronomical_dusk: sun::solar_event_time(location, dt, sun::SolarEvent::AstronomicalDusk)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
    };

    // Calculate moon position and events
    let moon_pos = moon::lunar_position(location, dt);
    let moon_events = MoonEvents {
        moonrise: moon::lunar_event_time(location, dt, moon::LunarEvent::Moonrise)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        moonset: moon::lunar_event_time(location, dt, moon::LunarEvent::Moonset)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
    };

    // Lunar phases for the month
    let phases = moon::lunar_phases(dt.year(), dt.month());
    let lunar_phases: Vec<LunarPhaseData> = phases
        .iter()
        .map(|p| {
            let phase_type = match p.phase_type {
                moon::LunarPhaseType::NewMoon => "new_moon",
                moon::LunarPhaseType::FirstQuarter => "first_quarter",
                moon::LunarPhaseType::FullMoon => "full_moon",
                moon::LunarPhaseType::LastQuarter => "last_quarter",
            };
            LunarPhaseData {
                phase_type: phase_type.to_string(),
                datetime: p.datetime.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
            }
        })
        .collect();

    let city_name_ref = city_name.as_deref();
    let ai_insights = if let Some(cfg) = ai_config {
        if cfg.enabled {
            let events =
                events::collect_events_within_window(location, dt, chrono::Duration::hours(12));
            let next_idx = events.iter().position(|(time, _)| *time > *dt);
            let summaries = ai::prepare_event_summaries(&events, dt, next_idx);

            let ai_data = ai::build_ai_data(ai::AiDataContext {
                location,
                timezone,
                dt,
                city_name: city_name_ref,
                sun_pos: &sun_pos,
                moon_pos: &moon_pos,
                events: summaries,
                time_sync_info,
                lunar_phases: &phases,
            });

            let outcome = match ai::fetch_insights(cfg, &ai_data) {
                Ok(outcome) => outcome,
                Err(err) => ai::AiOutcome::from_error(&cfg.model, err),
            };

            Some(build_ai_insights(&outcome, timezone))
        } else {
            None
        }
    } else {
        None
    };

    let output = JsonOutput {
        location: LocationData {
            latitude: location.latitude.value(),
            longitude: location.longitude.value(),
            timezone: timezone_name.to_string(),
            city: city_name,
        },
        datetime: DateTimeData {
            local: dt.format("%Y-%m-%d %H:%M:%S %Z").to_string(),
            utc: dt
                .with_timezone(&chrono::Utc)
                .format("%Y-%m-%d %H:%M:%S UTC")
                .to_string(),
            timezone_offset: dt.format("%:z").to_string(),
            time_sync: build_time_sync_data(time_sync_info),
        },
        sun: SunData {
            position: PositionData {
                altitude: sun_pos.altitude,
                azimuth: sun_pos.azimuth,
                azimuth_compass: coordinates::azimuth_to_compass(sun_pos.azimuth).to_string(),
            },
            events: sun_events,
        },
        moon: MoonData {
            position: MoonPositionData {
                altitude: moon_pos.altitude,
                azimuth: moon_pos.azimuth,
                azimuth_compass: coordinates::azimuth_to_compass(moon_pos.azimuth).to_string(),
                distance_km: moon_pos.distance,
                angular_diameter_arcmin: moon_pos.angular_diameter,
            },
            events: moon_events,
            phase: PhaseData {
                name: moon::phase_name(moon_pos.phase_angle).to_string(),
                emoji: moon::phase_emoji(moon_pos.phase_angle).to_string(),
                angle_degrees: moon_pos.phase_angle,
                illumination_percent: moon_pos.illumination * 100.0,
            },
        },
        lunar_phases,
        ai_insights,
    };

    Ok(serde_json::to_string_pretty(&output)?)
}

#[cfg(not(feature = "ai-insights"))]
fn generate_json_output_impl(
    location: &Location,
    timezone: &Tz,
    city_name: Option<String>,
    dt: &DateTime<Tz>,
    timezone_name: &str,
    time_sync_info: &time_sync::TimeSyncInfo,
    _ai_config: Option<&()>, // Placeholder parameter for type consistency
) -> Result<String> {
    // Calculate sun position and events
    let sun_pos = sun::solar_position(location, dt);
    let sun_events = SunEvents {
        sunrise: sun::solar_event_time(location, dt, sun::SolarEvent::Sunrise)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        sunset: sun::solar_event_time(location, dt, sun::SolarEvent::Sunset)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        solar_noon: sun::solar_event_time(location, dt, sun::SolarEvent::SolarNoon)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        civil_dawn: sun::solar_event_time(location, dt, sun::SolarEvent::CivilDawn)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        civil_dusk: sun::solar_event_time(location, dt, sun::SolarEvent::CivilDusk)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        nautical_dawn: sun::solar_event_time(location, dt, sun::SolarEvent::NauticalDawn)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        nautical_dusk: sun::solar_event_time(location, dt, sun::SolarEvent::NauticalDusk)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        astronomical_dawn: sun::solar_event_time(location, dt, sun::SolarEvent::AstronomicalDawn)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        astronomical_dusk: sun::solar_event_time(location, dt, sun::SolarEvent::AstronomicalDusk)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
    };

    // Calculate moon position and events
    let moon_pos = moon::lunar_position(location, dt);
    let moon_events = MoonEvents {
        moonrise: moon::lunar_event_time(location, dt, moon::LunarEvent::Moonrise)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
        moonset: moon::lunar_event_time(location, dt, moon::LunarEvent::Moonset)
            .map(|t| t.format("%Y-%m-%d %H:%M:%S %Z").to_string()),
    };

    // Calculate lunar phases for current month
    let phases = moon::lunar_phases(dt.year(), dt.month());
    let lunar_phases = phases
        .iter()
        .map(|p| {
            let phase_type = match p.phase_type {
                moon::LunarPhaseType::NewMoon => "new_moon",
                moon::LunarPhaseType::FirstQuarter => "first_quarter",
                moon::LunarPhaseType::FullMoon => "full_moon",
                moon::LunarPhaseType::LastQuarter => "last_quarter",
            };
            LunarPhaseData {
                phase_type: phase_type.to_string(),
                datetime: p.datetime.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
            }
        })
        .collect();

    let output = JsonOutput {
        location: LocationData {
            latitude: location.latitude.value(),
            longitude: location.longitude.value(),
            timezone: timezone_name.to_string(),
            city: city_name,
        },
        datetime: DateTimeData {
            local: dt.format("%Y-%m-%d %H:%M:%S %Z").to_string(),
            utc: dt
                .with_timezone(&chrono::Utc)
                .format("%Y-%m-%d %H:%M:%S UTC")
                .to_string(),
            timezone_offset: dt.format("%:z").to_string(),
            time_sync: build_time_sync_data(time_sync_info),
        },
        sun: SunData {
            position: PositionData {
                altitude: sun_pos.altitude,
                azimuth: sun_pos.azimuth,
                azimuth_compass: coordinates::azimuth_to_compass(sun_pos.azimuth).to_string(),
            },
            events: sun_events,
        },
        moon: MoonData {
            position: MoonPositionData {
                altitude: moon_pos.altitude,
                azimuth: moon_pos.azimuth,
                azimuth_compass: coordinates::azimuth_to_compass(moon_pos.azimuth).to_string(),
                distance_km: moon_pos.distance,
                angular_diameter_arcmin: moon_pos.angular_diameter,
            },
            events: moon_events,
            phase: PhaseData {
                name: moon::phase_name(moon_pos.phase_angle).to_string(),
                emoji: moon::phase_emoji(moon_pos.phase_angle).to_string(),
                angle_degrees: moon_pos.phase_angle,
                illumination_percent: moon_pos.illumination * 100.0,
            },
        },
        lunar_phases,
        ai_insights: None, // AI insights not available without the feature
    };

    Ok(serde_json::to_string_pretty(&output)?)
}

fn build_time_sync_data(time_sync_info: &time_sync::TimeSyncInfo) -> TimeSyncData {
    match (time_sync_info.delta, time_sync_info.direction()) {
        (Some(delta), Some(direction)) => TimeSyncData {
            source: time_sync_info.source.to_string(),
            delta_seconds: time_sync_info.delta_seconds(),
            offset_display: Some(time_sync::format_offset(delta)),
            status: time_sync::direction_code(direction).to_string(),
            error: None,
        },
        (Some(delta), None) => TimeSyncData {
            source: time_sync_info.source.to_string(),
            delta_seconds: time_sync_info.delta_seconds(),
            offset_display: Some(time_sync::format_offset(delta)),
            status: "measurable".to_string(),
            error: None,
        },
        _ => TimeSyncData {
            source: time_sync_info.source.to_string(),
            delta_seconds: None,
            offset_display: None,
            status: if time_sync_info.error.is_some() {
                "error".to_string()
            } else {
                "unavailable".to_string()
            },
            error: time_sync_info.error.clone(),
        },
    }
}

#[cfg(feature = "ai-insights")]
fn build_ai_insights(outcome: &ai::AiOutcome, timezone: &Tz) -> AiInsightsData {
    let elapsed = Utc::now().signed_duration_since(outcome.updated_at);
    let elapsed_secs = elapsed.num_seconds().max(0);
    let minutes = elapsed_secs / 60;
    let seconds = elapsed_secs % 60;
    let elapsed_display = format!("Updated {:02}:{:02} ago", minutes, seconds);

    AiInsightsData {
        model: outcome.model.clone(),
        updated_at: outcome
            .updated_at
            .with_timezone(timezone)
            .format("%Y-%m-%d %H:%M:%S %Z")
            .to_string(),
        updated_elapsed: Some(elapsed_display),
        summary: outcome.content.clone(),
        error: outcome.error.clone(),
    }
}