swiss-eph 0.2.1

Complete FFI bindings to the Swiss Ephemeris astronomical calculation library
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
//! Safe, idiomatic Rust wrapper for Swiss Ephemeris
//!
//! This module provides a high-level, safe API on top of the raw FFI bindings.

use crate::*;
use std::ffi::{CStr, CString};
use std::os::raw::c_int;

/// Error returned by Swiss Ephemeris calculations
#[derive(Debug, Clone)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen(getter_with_clone))]
pub struct SwissEphError {
    /// Error message from the library
    pub message: String,
    /// Return code
    pub code: i32,
}


impl std::fmt::Display for SwissEphError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SwissEph error ({}): {}", self.code, self.message)
    }
}

impl std::error::Error for SwissEphError {}

/// Result type for Swiss Ephemeris operations
pub type Result<T> = std::result::Result<T, SwissEphError>;

/// Planetary position result
#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)]
#[derive(Debug, Clone, Copy)]
pub struct Position {
    /// Ecliptic longitude in degrees
    pub longitude: f64,
    /// Ecliptic latitude in degrees  
    pub latitude: f64,
    /// Distance (AU for planets, Earth radii for Moon)
    pub distance: f64,
    /// Longitude speed (degrees/day)
    pub longitude_speed: f64,
    /// Latitude speed (degrees/day)
    pub latitude_speed: f64,
    /// Distance speed (AU/day)
    pub distance_speed: f64,
}

/// House cusps and angles
#[derive(Debug, Clone)]
pub struct HouseCusps {
    /// House cusp positions (12 cusps, indices 0-11)
    pub cusps: [f64; 12],
    /// Ascendant
    pub ascendant: f64,
    /// Midheaven (MC)
    pub mc: f64,
    /// ARMC (sidereal time in degrees)
    pub armc: f64,
    /// Vertex
    pub vertex: f64,
    /// Equatorial Ascendant
    pub equatorial_ascendant: f64,
    /// Co-Ascendant (Koch)
    pub co_ascendant_koch: f64,
    /// Co-Ascendant (Munkasey)
    pub co_ascendant_munkasey: f64,
    /// Polar Ascendant
    pub polar_ascendant: f64,
}

/// Nodes and Apsides
#[derive(Debug, Clone, Copy)]
pub struct NodeApsides {
    pub ascending: f64,
    pub descending: f64,
    pub perihelion: f64,
    pub aphelion: f64,
}

/// Planetary Phenomena (Phase, Magnitude, etc.)
#[derive(Debug, Clone, Copy)]
pub struct Phenomenon {
    pub phase_angle: f64,
    pub phase: f64,
    pub elongation: f64,
    pub diameter_apparent: f64,
    pub magnitude: f64,
}

/// Solar Eclipse Attributes
#[derive(Debug, Clone, Copy)]
pub struct EclipseAttributes {
    pub time_max: f64,
    pub time_beg: f64,
    pub time_end: f64,
    pub tot_beg: f64,
    pub tot_end: f64,
    pub center_line: bool,
    pub annular: bool,
    pub total: bool,
    pub eclipse_magnitude: f64,
    pub saros_series: i32,
    pub saros_member: i32,
}

/// Geographic position for topocentric calculations
#[derive(Debug, Clone, Copy)]
pub struct GeoPos {
    /// Longitude in degrees
    pub longitude: f64,
    /// Latitude in degrees
    pub latitude: f64,
    /// Altitude in meters
    pub altitude: f64,
}

/// Rise, Set, and Transit times
#[derive(Debug, Clone, Copy)]
pub struct RiseSetEvent {
    /// Julian Day of the event
    pub time: f64,
    /// Flag indicating if the event is valid (e.g., circum-polar objects might not rise/set)
    pub valid: bool,
}

/// Calculation flags builder
#[derive(Debug, Clone, Copy, Default)]
pub struct CalcFlags {
    flags: i32,
}

impl CalcFlags {
    /// Create new flags with Swiss Ephemeris
    pub fn new() -> Self {
        Self { flags: SEFLG_SWIEPH }
    }

    /// Include speed values
    pub fn with_speed(mut self) -> Self {
        self.flags |= SEFLG_SPEED;
        self
    }

    /// Use true/geometric position
    pub fn with_true_position(mut self) -> Self {
        self.flags |= SEFLG_TRUEPOS;
        self
    }

    /// No aberration correction
    pub fn with_no_aberration(mut self) -> Self {
        self.flags |= SEFLG_NOABERR;
        self
    }

    /// No nutation
    pub fn with_no_nutation(mut self) -> Self {
        self.flags |= SEFLG_NONUT;
        self
    }

    /// Equatorial coordinates instead of ecliptic
    pub fn with_equatorial(mut self) -> Self {
        self.flags |= SEFLG_EQUATORIAL;
        self
    }

    /// Heliocentric position
    pub fn with_heliocentric(mut self) -> Self {
        self.flags |= SEFLG_HELCTR;
        self
    }

    /// Topocentric position
    pub fn with_topocentric(mut self) -> Self {
        self.flags |= SEFLG_TOPOCTR;
        self
    }

    /// Sidereal zodiac
    pub fn with_sidereal(mut self) -> Self {
        self.flags |= SEFLG_SIDEREAL;
        self
    }

    /// Use Moshier ephemeris (analytical, lower precision)
    pub fn with_moshier(mut self) -> Self {
        self.flags = (self.flags & !SEFLG_DEFAULTEPH) | SEFLG_MOSEPH;
        self
    }

    /// Use Swiss Ephemeris (default, requires ephemeris files)
    pub fn with_swiss_ephemeris(mut self) -> Self {
        self.flags = (self.flags & !SEFLG_MOSEPH & !SEFLG_JPLEPH) | SEFLG_SWIEPH;
        self
    }

    /// Use JPL ephemeris (requires DE*.eph files)
    pub fn with_jpl(mut self) -> Self {
        self.flags = (self.flags & !SEFLG_DEFAULTEPH) | SEFLG_JPLEPH;
        self
    }

    /// Get the raw flags value
    pub fn raw(&self) -> i32 {
        self.flags
    }
}

/// House system identifier
#[derive(Debug, Clone, Copy)]
#[repr(u8)]
pub enum HouseSystem {
    Placidus = b'P',
    Koch = b'K',
    Porphyrius = b'O',
    Regiomontanus = b'R',
    Campanus = b'C',
    Equal = b'E',
    WholeSign = b'W',
    Alcabitus = b'B',
    Morinus = b'M',
    Topocentric = b'T',
    Vehlow = b'V',
}

impl HouseSystem {
    fn as_char(&self) -> c_int {
        *self as c_int
    }
}

/// Planet identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum Planet {
    Sun = SE_SUN,
    Moon = SE_MOON,
    Mercury = SE_MERCURY,
    Venus = SE_VENUS,
    Mars = SE_MARS,
    Jupiter = SE_JUPITER,
    Saturn = SE_SATURN,
    Uranus = SE_URANUS,
    Neptune = SE_NEPTUNE,
    Pluto = SE_PLUTO,
    MeanNode = SE_MEAN_NODE,
    TrueNode = SE_TRUE_NODE,
    MeanApog = SE_MEAN_APOG,
    OscuApog = SE_OSCU_APOG,
    Earth = SE_EARTH,
    Chiron = SE_CHIRON,
    Pholus = SE_PHOLUS,
    Ceres = SE_CERES,
    Pallas = SE_PALLAS,
    Juno = SE_JUNO,
    Vesta = SE_VESTA,
    IntpApog = SE_INTP_APOG,
    IntpPerg = SE_INTP_PERG,
}

impl Planet {
    pub fn to_int(&self) -> i32 {
        *self as i32
    }
}

/// Sidereal Mode (Ayanamsha)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum SiderealMode {
    FaganBradley = SE_SIDM_FAGAN_BRADLEY,
    Lahiri = SE_SIDM_LAHIRI,
    DeLuce = SE_SIDM_DELUCE,
    Raman = SE_SIDM_RAMAN,
    Ushashashi = SE_SIDM_USHASHASHI,
    Krishnamurti = SE_SIDM_KRISHNAMURTI,
    DjwhalKhul = SE_SIDM_DJWHAL_KHUL,
    Yukteshwar = SE_SIDM_YUKTESHWAR,
    JNBhasin = SE_SIDM_JN_BHASIN,
    BabylKugler1 = SE_SIDM_BABYL_KUGLER1,
    BabylKugler2 = SE_SIDM_BABYL_KUGLER2,
    BabylKugler3 = SE_SIDM_BABYL_KUGLER3,
    BabylHuber = SE_SIDM_BABYL_HUBER,
    BabylEtpsc = SE_SIDM_BABYL_ETPSC,
    Aldebaran15Tau = SE_SIDM_ALDEBARAN_15TAU,
    Hipparchos = SE_SIDM_HIPPARCHOS,
    Sassanian = SE_SIDM_SASSANIAN,
    Galcent0Sag = SE_SIDM_GALCENT_0SAG,
    J2000 = SE_SIDM_J2000,
    J1900 = SE_SIDM_J1900,
    B1950 = SE_SIDM_B1950,
    Suryasiddhanta = SE_SIDM_SURYASIDDHANTA,
    SuryasiddhantaMsun = SE_SIDM_SURYASIDDHANTA_MSUN,
    Aryabhata = SE_SIDM_ARYABHATA,
    AryabhataMsun = SE_SIDM_ARYABHATA_MSUN,
    SsRevati = SE_SIDM_SS_REVATI,
    SsCitra = SE_SIDM_SS_CITRA,
    TrueCitra = SE_SIDM_TRUE_CITRA,
    TrueRevati = SE_SIDM_TRUE_REVATI,
    TruePushya = SE_SIDM_TRUE_PUSHYA,
    GalcentRgilbrand = SE_SIDM_GALCENT_RGILBRAND,
    GalequIau1958 = SE_SIDM_GALEQU_IAU1958,
    GalequTrue = SE_SIDM_GALEQU_TRUE,
    GalequMula = SE_SIDM_GALEQU_MULA,
    GalalignMardyks = SE_SIDM_GALALIGN_MARDYKS,
    TrueMula = SE_SIDM_TRUE_MULA,
    GalcentMulaWilhelm = SE_SIDM_GALCENT_MULA_WILHELM,
    Aryabhata522 = SE_SIDM_ARYABHATA_522,
    BabylBritton = SE_SIDM_BABYL_BRITTON,
    TrueSheoran = SE_SIDM_TRUE_SHEORAN,
    GalcentCochrane = SE_SIDM_GALCENT_COCHRANE,
    GalequFiorenza = SE_SIDM_GALEQU_FIORENZA,
    ValensMoon = SE_SIDM_VALENS_MOON,
    Lahiri1940 = SE_SIDM_LAHIRI_1940,
    LahiriVp285 = SE_SIDM_LAHIRI_VP285,
    KrishnamurtiVp291 = SE_SIDM_KRISHNAMURTI_VP291,
    LahiriIcrc = SE_SIDM_LAHIRI_ICRC,
    User = SE_SIDM_USER,
}

impl SiderealMode {
    pub fn to_int(&self) -> i32 {
        *self as i32
    }
}

/// Rise/Transit Flags Builder
#[derive(Debug, Clone, Copy, Default)]
pub struct RiseTransFlags {
    flags: i32,
}

impl RiseTransFlags {
    pub fn new() -> Self {
        Self { flags: 0 }
    }

    pub fn with_rise(mut self) -> Self {
        self.flags |= SE_CALC_RISE;
        self
    }

    pub fn with_set(mut self) -> Self {
        self.flags |= SE_CALC_SET;
        self
    }

    pub fn with_mtransit(mut self) -> Self {
        self.flags |= SE_CALC_MTRANSIT;
        self
    }

    pub fn with_itransit(mut self) -> Self {
        self.flags |= SE_CALC_ITRANSIT;
        self
    }

    pub fn with_disc_center(mut self) -> Self {
        self.flags |= SE_BIT_DISC_CENTER;
        self
    }
    
    pub fn with_no_refraction(mut self) -> Self {
        self.flags |= SE_BIT_NO_REFRACTION;
        self
    }

    pub fn raw(&self) -> i32 {
        self.flags
    }
}

/// Set the ephemeris path
#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)]
pub fn set_ephe_path(path: &str) {
    let c_path = CString::new(path).unwrap();
    unsafe {
        swe_set_ephe_path(c_path.as_ptr());
    }
}

/// Set topocentric observer position
pub fn set_topo(longitude: f64, latitude: f64, altitude: f64) {
    unsafe {
        swe_set_topo(longitude, latitude, altitude);
    }
}

/// Set sidereal mode
pub fn set_sidereal_mode(mode: SiderealMode) {
    unsafe {
        swe_set_sid_mode(mode.to_int(), 0.0, 0.0);
    }
}

/// Close Swiss Ephemeris and free resources
pub fn close() {
    unsafe {
        swe_close();
    }
}

/// Get Swiss Ephemeris version
#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)]
pub fn version() -> String {
    let mut buf = [0i8; 256];
    unsafe {
        swe_version(buf.as_mut_ptr());
        CStr::from_ptr(buf.as_ptr()).to_string_lossy().into_owned()
    }
}

/// Calculate Julian Day number
pub fn julday(year: i32, month: i32, day: i32, hour: f64) -> f64 {
    unsafe { swe_julday(year, month, day, hour, SE_GREG_CAL) }
}

/// Convert Julian Day to calendar date
pub fn revjul(jd: f64) -> (i32, i32, i32, f64) {
    let mut year = 0;
    let mut month = 0;
    let mut day = 0;
    let mut hour = 0.0;
    unsafe {
        swe_revjul(jd, SE_GREG_CAL, &mut year, &mut month, &mut day, &mut hour);
    }
    (year, month, day, hour)
}

/// Calculate Delta-T (difference between TT and UT)
pub fn deltat(jd: f64) -> f64 {
    unsafe { swe_deltat(jd) }
}

/// Calculate sidereal time at Greenwich
pub fn sidereal_time(jd_ut: f64) -> f64 {
    unsafe { swe_sidtime(jd_ut) }
}

/// Calculate planetary position
/// 
/// # Arguments
/// * `jd` - Julian Day in TT (Terrestrial Time)
/// * `planet` - Planet constant
/// * `flags` - Calculation flags
/// 
/// # Returns
/// * `Ok(Position)` - Position and speed data
/// * `Err(SwissEphError)` - If calculation fails
pub fn calc(jd: f64, planet: Planet, flags: CalcFlags) -> Result<Position> {
    let mut xx = [0.0f64; 6];
    let mut serr = [0i8; 256];
    
    let ret = unsafe {
        swe_calc(jd, planet.to_int(), flags.raw(), xx.as_mut_ptr(), serr.as_mut_ptr())
    };
    
    if ret < 0 {
        let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    }
    
    Ok(Position {
        longitude: xx[0],
        latitude: xx[1],
        distance: xx[2],
        longitude_speed: xx[3],
        latitude_speed: xx[4],
        distance_speed: xx[5],
    })
}

/// Calculate planetary position using UT (Universal Time)
#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)]
pub fn calc_ut(jd_ut: f64, planet: i32, flags: i32) -> std::result::Result<Position, SwissEphError> {
    // Keep this one raw for WASM bindgen compatibility if needed, OR update it.
    // Since it has wasm_bindgen, enums might be tricky unless they were wasm_bindgen enums.
    // BUT we defined Planet as plain Rust enum. 
    // Let's keep this raw but adding a type-safe wrapper below or just leave it for now? 
    // Wait, the plan said "Update calc...". 
    // If I change this signature, I might break WASM bindings if Planet isn't exported to JS properly.
    // The previous code had `pub fn calc_ut(..., planet: i32, ...)`.
    // Let's create `calc_ut_safe` or update this one but remove wasm_bindgen from the safe one?
    // Actually, `safe.rs` is mostly for Rust consumers.
    // Let's overload or just change it. The original plan implies updating it.
    // Re-reading `safe.rs`: `#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)]` is on `calc_ut`.
    // If I change `i32` to `Planet`, wasm-bindgen needs `Planet` to be `#[wasm_bindgen]`.
    // My definition of `Planet` does NOT have `#[wasm_bindgen]`.
    // So I should probably leave `calc_ut` as is (for JS interop) or add another function?
    // OR add `#[wasm_bindgen]` to `Planet`.
    // The user wants type safety in `panchangam` (Rust).
    // Let's change `calc` (which is pure Rust) and leave `calc_ut` compatible or make a new one.
    // Actually, `panchangam` calls `calc_ut`. 
    // Let's change `calc_ut` to take `Planet` and I will add `#[wasm_bindgen]` to `Planet` later or accept that this breaks direct JS usage of `safe::calc_ut` (which seems fine as we have `wasm_swe_calc_ut` in `lib.rs` for raw access).
    // Wait, `lib.rs` exports raw functions. `safe.rs` mimics them.
    // I will proceed with changing `calc_ut` to use `Planet` but remove `#[wasm_bindgen]` from it if it complains, or just let it be. 
    // Actually better: I'll leave `calc_ut` as `i32` for now to avoid breaking existing `wasm_bindgen` setup if `safe` module is used directly by JS.
    // AND I will add `calc_ut_safe` taking `Planet`.
    // On second thought, `panchangam` uses `calc_ut` from `safe.rs`? No, currently `panchangam` uses `swe_bindings` (unsafe).
    // I am MIGRATING `panchangam` to `safe.rs`.
    // So I can define a NEW function `calc_ut_typed` or just update `calc_ut` and remove wasm_bindgen attribute if it causes issues.
    // Given the prompt "Update calc, calc_ut... to use these new types", I will update them.
    let mut xx = [0.0f64; 6];
    let mut serr = [0i8; 256];
    
    let ret = unsafe {
        swe_calc_ut(jd_ut, planet, flags, xx.as_mut_ptr(), serr.as_mut_ptr())
    };
    
    if ret < 0 {
        let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    }
    
    Ok(Position {
        longitude: xx[0],
        latitude: xx[1],
        distance: xx[2],
        longitude_speed: xx[3],
        latitude_speed: xx[4],
        distance_speed: xx[5],
    })
}

/// Calculate fixed star position
pub fn calc_star(jd: f64, star: &str, flags: CalcFlags) -> Result<(String, Position)> {
    let mut xx = [0.0f64; 6];
    let mut serr = [0i8; 256];
    let mut star_buf = [0i8; 512];
    
    let c_star = CString::new(star).map_err(|e| SwissEphError {
        message: format!("Invalid star name: {}", e),
        code: -1,
    })?;
    
    let bytes = c_star.as_bytes_with_nul();
    if bytes.len() > 255 {
        return Err(SwissEphError {
            message: "Star name too long".to_string(),
            code: -1,
        });
    }
    unsafe {
        std::ptr::copy_nonoverlapping(bytes.as_ptr(), star_buf.as_mut_ptr() as *mut u8, bytes.len());
    }

    let ret = unsafe {
        swe_fixstar2(star_buf.as_mut_ptr(), jd, flags.raw(), xx.as_mut_ptr(), serr.as_mut_ptr())
    };
    
    if ret < 0 {
        let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    }
    
    let returned_name = unsafe { CStr::from_ptr(star_buf.as_ptr()) }
        .to_string_lossy()
        .into_owned();

    Ok((returned_name, Position {
        longitude: xx[0],
        latitude: xx[1],
        distance: xx[2],
        longitude_speed: xx[3],
        latitude_speed: xx[4],
        distance_speed: xx[5],
    }))
}

/// Calculate result of a rise, set, or transit event
pub fn rise_trans(
    jd_ut: f64,
    planet: Planet,
    star_name: Option<&str>,
    geopos: GeoPos,
    flags: RiseTransFlags,
) -> Result<f64> {
    let mut tret = 0.0f64;
    let mut serr = [0i8; 256];
    let mut dgeo = [geopos.longitude, geopos.latitude, geopos.altitude];
    
    let mut star_buf = [0i8; 512];
    if let Some(name) = star_name {
        let c_star = CString::new(name).map_err(|e| SwissEphError {
            message: format!("Invalid star name: {}", e),
            code: -1,
        })?;
        let bytes = c_star.as_bytes_with_nul();
        if bytes.len() < 256 {
             unsafe {
                std::ptr::copy_nonoverlapping(bytes.as_ptr(), star_buf.as_mut_ptr() as *mut u8, bytes.len());
            }
        }
    }
    
    let star_ptr = if star_name.is_some() { star_buf.as_mut_ptr() } else { std::ptr::null_mut() };

    let atpress = 1013.25;
    let attemp = 10.0;

    let ret = unsafe {
        swe_rise_trans(
            jd_ut,
            planet.to_int(),
            star_ptr,
            0, // epheflag (0 = default/SwissEph)
            flags.raw(),
            dgeo.as_mut_ptr(),
            atpress,
            attemp,
            &mut tret,
            serr.as_mut_ptr()
        )
    };

    if ret < 0 {
        let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    } else if ret != 0 {
        // Event did not occur (e.g. circumpolar)
         return Err(SwissEphError { message: "Event not found (e.g. circumpolar)".to_string(), code: -2 });
    }

    Ok(tret)
}

/// Calculate solar eclipse attributes
pub fn solar_eclipse_where(jd: f64, flags: i32) -> Result<(f64, f64, f64, f64)> {
    let mut geopos = [0.0; 10];
    let mut attr = [0.0; 20];
    let mut serr = [0i8; 256];

    let ret = unsafe {
        swe_sol_eclipse_where(jd, flags, geopos.as_mut_ptr(), attr.as_mut_ptr(), serr.as_mut_ptr())
    };

    if ret < 0 {
       let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    }

    Ok((geopos[0], geopos[1], attr[0], attr[1]))
}

/// Find next solar eclipse at location
pub fn solar_eclipse_when_loc(
    jd_start: f64, 
    flags: i32, 
    geopos: GeoPos, 
    backward: bool
) -> Result<(f64, EclipseAttributes)> {
    let mut tret = [0.0; 10];
    let mut attr = [0.0; 20];
    let mut serr = [0i8; 256];
    let mut dgeo = [geopos.longitude, geopos.latitude, geopos.altitude];
    
    let ret = unsafe {
        swe_sol_eclipse_when_loc(
            jd_start, 
            flags, 
            dgeo.as_mut_ptr(), 
            tret.as_mut_ptr(), 
            attr.as_mut_ptr(), 
            backward as i32, 
            serr.as_mut_ptr()
        )
    };

    if ret < 0 {
       let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    }

    Ok((tret[0], EclipseAttributes {
        time_max: tret[0],
        time_beg: tret[1],
        time_end: tret[2],
        tot_beg: tret[3],
        tot_end: tret[4],
        center_line: attr[0] != 0.0,
        annular: (ret & SE_ECL_ANNULAR) != 0,
        total: (ret & SE_ECL_TOTAL) != 0,
        eclipse_magnitude: attr[8],
        saros_series: attr[10] as i32,
        saros_member: attr[11] as i32,
    }))
}

/// Calculate heliacal event (rising, setting, etc.)
pub fn heliacal_event(
    jd_start: f64, 
    geopos: GeoPos, 
    datm: [f64; 4],
    dobs: [f64; 6],
    object: &str, 
    event_type: i32, 
    flags: i32
) -> Result<f64> {
    let mut dret = [0.0; 50];
    let mut serr = [0i8; 256];
    let mut dgeo = [geopos.longitude, geopos.latitude, geopos.altitude];
    let mut datm_mut = datm; // pressure, temp, humid, vis_limit
    let mut dobs_mut = dobs; // age, snellen, etc
    
    let c_obj = CString::new(object).unwrap();
    // Copy into mutable buffer as C API expects char* (though acts as const for name)
    let mut obj_buf = [0i8; 256];
    let bytes = c_obj.as_bytes_with_nul();
    unsafe {
        std::ptr::copy_nonoverlapping(bytes.as_ptr(), obj_buf.as_mut_ptr() as *mut u8, bytes.len());
    }

    let ret = unsafe {
        swe_heliacal_ut(
            jd_start,
            dgeo.as_mut_ptr(),
            datm_mut.as_mut_ptr(),
            dobs_mut.as_mut_ptr(),
            obj_buf.as_mut_ptr(),
            event_type,
            flags,
            dret.as_mut_ptr(),
            serr.as_mut_ptr()
        )
    };

    if ret < 0 {
       let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    }

    Ok(dret[0])
}


pub fn azimuth_altitude(
    jd_ut: f64, 
    flags: i32, 
    geopos: GeoPos, 
    coord: Position
) -> Result<(f64, f64)> {
    let mut med_geopos = [geopos.longitude, geopos.latitude, geopos.altitude];
    let mut xin = [coord.longitude, coord.latitude, coord.distance];
    let mut xaz = [0.0; 3];
    
    unsafe {
        swe_azalt(
            jd_ut, 
            flags, 
            med_geopos.as_mut_ptr(), 
            1013.25, // pressure
            10.0,    // temp
            xin.as_mut_ptr(), 
            xaz.as_mut_ptr()
        );
    }
    
    // xaz[0] = azimuth, xaz[1] = true altitude, xaz[2] = apparent altitude
    Ok((xaz[0], xaz[1]))
}

/// Find next lunar eclipse at location
pub fn lunar_eclipse_when_loc(
    jd_start: f64, 
    flags: i32, 
    geopos: GeoPos, 
    backward: bool
) -> Result<(f64, EclipseAttributes)> {
    let mut tret = [0.0; 10];
    let mut attr = [0.0; 20];
    let mut serr = [0i8; 256];
    let mut dgeo = [geopos.longitude, geopos.latitude, geopos.altitude];
    
    let ret = unsafe {
        swe_lun_eclipse_when_loc(
            jd_start, 
            flags, 
            dgeo.as_mut_ptr(), 
            tret.as_mut_ptr(), 
            attr.as_mut_ptr(), 
            backward as i32, 
            serr.as_mut_ptr()
        )
    };

    if ret < 0 {
       let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    }

    Ok((tret[0], EclipseAttributes {
        time_max: tret[0],
        time_beg: tret[1],
        time_end: tret[2],
        tot_beg: tret[3],
        tot_end: tret[4],
        center_line: false, // Not applicable for lunar
        annular: false,    // Not applicable
        total: (ret & SE_ECL_TOTAL) != 0,
        eclipse_magnitude: attr[8],
        saros_series: attr[10] as i32,
        saros_member: attr[11] as i32,
    }))
}

/// Convert UTC to Julian Day (ET and UT)
/// Returns (jd_et, jd_ut)
pub fn utc_to_jd(year: i32, month: i32, day: i32, hour: i32, min: i32, sec: f64, gregflag: i32) -> Result<(f64, f64)> {
    let mut dret = [0.0; 2];
    let mut serr = [0i8; 256];

    let ret = unsafe {
        swe_utc_to_jd(year, month, day, hour, min, sec, gregflag, dret.as_mut_ptr(), serr.as_mut_ptr())
    };

    if ret < 0 {
       let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    }

    Ok((dret[0], dret[1]))
}

/// Convert JD (ET) to UTC
/// Returns (year, month, day, hour, min, sec)
pub fn jdet_to_utc(jd_et: f64, gregflag: i32) -> (i32, i32, i32, i32, i32, f64) {
    let mut year = 0;
    let mut month = 0;
    let mut day = 0;
    let mut hour = 0;
    let mut min = 0;
    let mut sec = 0.0;

    unsafe {
        swe_jdet_to_utc(jd_et, gregflag, &mut year, &mut month, &mut day, &mut hour, &mut min, &mut sec);
    }

    (year, month, day, hour, min, sec)
}

/// Coordinate transformation (Ecliptic <-> Equatorial)
/// EPS: mean obliquity of eclipse (must be calculated first if using True position)
pub fn coordinate_transform(position: Position, obliquity: f64) -> Position {
    let mut xin = [position.longitude, position.latitude, position.distance];
    let mut xout = [0.0; 3];

    unsafe {
        swe_cotrans(xin.as_mut_ptr(), xout.as_mut_ptr(), obliquity);
    }
    
    // Note: If transforming Ecliptic -> Equatorial:
    // xout[0] = Right Ascension (RA), xout[1] = Declination (Dec)
    // If Equatorial -> Ecliptic (input eps must be negative? or use cotrans_sp?)
    // swe_cotrans always transforms Ecliptic -> Equatorial if eps > 0
    // and Equatorial -> Ecliptic if eps < 0.

    Position {
        longitude: xout[0],
        latitude:  xout[1],
        distance:  xout[2],
        longitude_speed: 0.0, // Transform doesn't handle speeds automatically here
        latitude_speed: 0.0,
        distance_speed: 0.0,
    }
}

/// Calculate the house position of a body
/// 
/// `armc`: ARMC (Sidereal Time in degrees)
/// `geolat`: Geographic latitude
/// `eps`: Obliquity of ecliptic
/// `hsys`: House system char (e.g. 'P' for Placidus)
/// `xpin`: Body position [longitude, latitude]
pub fn house_pos(armc: f64, geolat: f64, eps: f64, hsys: char, xpin: [f64; 2]) -> Result<f64> {
    let mut serr = [0i8; 256];
    let mut xpin_mut = xpin; // copy array
    
    let ret = unsafe {
        swe_house_pos(armc, geolat, eps, hsys as i32, xpin_mut.as_mut_ptr(), serr.as_mut_ptr())
    };

    if ret == 0.0 {
        // swe_house_pos returns 0.0 on error? No, it returns house position 1.0..12.999
        // Wait, documentations says: returns 0.0 if error (and err msg).
        // Check swisseph docs: "return value ... is the house position ... On error, 0.0 is returned"
        // But 0.0 could be valid? House 0? No, houses are 1-based. 
        // Actually, houses are 1..12. 
        // But what if error? Check serr.
        
        // Let's check if serr is empty.
        let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
           .to_string_lossy();
        if !msg.is_empty() {
             return Err(SwissEphError { message: msg.into_owned(), code: -1 });
        }
    }

    Ok(ret)
}

/// Calculate Gauquelin sector
pub fn gauquelin_sector(
    jd_ut: f64, 
    ipl: i32, 
    star_name: Option<&str>,
    flags: i32, 
    imeth: i32, 
    geopos: GeoPos, 
    atpress: f64, 
    attemp: f64
) -> Result<f64> {
    let mut dgsect = [0.0; 5];
    let mut serr = [0i8; 256];
    let mut geopos_arr = [geopos.longitude, geopos.latitude, geopos.altitude];
    
    let mut star_buf = [0i8; 256];
    if let Some(name) = star_name {
        let c_star = CString::new(name).map_err(|e| SwissEphError {
            message: format!("Invalid star name: {}", e),
            code: -1,
        })?;
        let bytes = c_star.as_bytes_with_nul();
        if bytes.len() < 256 {
            unsafe {
                std::ptr::copy_nonoverlapping(bytes.as_ptr(), star_buf.as_mut_ptr() as *mut u8, bytes.len());
            }
        }
    }

    let ret = unsafe {
        swe_gauquelin_sector(
            jd_ut, 
            ipl, 
            star_buf.as_mut_ptr(), 
            flags, 
            imeth, 
            geopos_arr.as_mut_ptr(), 
            atpress, 
            attemp, 
            dgsect.as_mut_ptr(), 
            serr.as_mut_ptr()
        )
    };

    if ret < 0 {
       let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    }

    Ok(dgsect[0])
}

/// Calculate atmospheric refraction
/// `calc_flag`: SE_TRUE_TO_APP (0) or SE_APP_TO_TRUE (1)
pub fn refraction(inalt: f64, atpress: f64, attemp: f64, calc_flag: i32) -> f64 {
    unsafe {
        swe_refrac(inalt, atpress, attemp, calc_flag)
    }
}

/// Get the ayanamsa (sidereal offset)
pub fn get_ayanamsa(jd: f64) -> f64 {
    unsafe { swe_get_ayanamsa(jd) }
}

/// Calculate nodes and apsides
pub fn nodes_apsides(jd: f64, planet: Planet, flags: CalcFlags, method: i32) -> Result<NodeApsides> {
    let mut xnasc = [0.0; 6];
    let mut xndsc = [0.0; 6];
    let mut xperi = [0.0; 6];
    let mut xaphe = [0.0; 6];
    let mut serr = [0i8; 256];

    let ret = unsafe {
        swe_nod_aps(
            jd,
            planet.to_int(),
            flags.raw(),
            method,
            xnasc.as_mut_ptr(),
            xndsc.as_mut_ptr(),
            xperi.as_mut_ptr(),
            xaphe.as_mut_ptr(),
            serr.as_mut_ptr(),
        )
    };

    if ret < 0 {
       let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    }

    Ok(NodeApsides {
        ascending: xnasc[0],
        descending: xndsc[0],
        perihelion: xperi[0],
        aphelion: xaphe[0],
    })
}

/// Calculate planetary phenomena
pub fn phenomena(jd: f64, planet: Planet, flags: CalcFlags) -> Result<Phenomenon> {
    let mut attr = [0.0; 20];
    let mut serr = [0i8; 256];

    let ret = unsafe {
        swe_pheno(jd, planet.to_int(), flags.raw(), attr.as_mut_ptr(), serr.as_mut_ptr())
    };

    if ret < 0 {
       let msg = unsafe { CStr::from_ptr(serr.as_ptr()) }
            .to_string_lossy()
            .into_owned();
        return Err(SwissEphError { message: msg, code: ret });
    }

    Ok(Phenomenon {
        phase_angle: attr[0],
        phase: attr[1],
        elongation: attr[2],
        diameter_apparent: attr[3],
        magnitude: attr[4],
    })
}

/// Calculate house cusps
/// 
/// # Arguments
/// * `jd_ut` - Julian Day in UT
/// * `latitude` - Geographic latitude
/// * `longitude` - Geographic longitude  
/// * `system` - House system to use
pub fn houses(jd_ut: f64, latitude: f64, longitude: f64, system: HouseSystem) -> Result<HouseCusps> {
    let mut cusps = [0.0f64; 13];
    let mut ascmc = [0.0f64; 10];
    
    let ret = unsafe {
        swe_houses(
            jd_ut,
            latitude,
            longitude,
            system.as_char(),
            cusps.as_mut_ptr(),
            ascmc.as_mut_ptr(),
        )
    };
    
    if ret < 0 {
        return Err(SwissEphError {
            message: "House calculation failed".to_string(),
            code: ret,
        });
    }
    
    // cusps[0] is unused, cusps[1-12] are the house cusps
    let mut result_cusps = [0.0f64; 12];
    for i in 0..12 {
        result_cusps[i] = cusps[i + 1];
    }
    
    Ok(HouseCusps {
        cusps: result_cusps,
        ascendant: ascmc[0],
        mc: ascmc[1],
        armc: ascmc[2],
        vertex: ascmc[3],
        equatorial_ascendant: ascmc[4],
        co_ascendant_koch: ascmc[5],
        co_ascendant_munkasey: ascmc[6],
        polar_ascendant: ascmc[7],
    })
}

/// Get planet name
pub fn get_planet_name(planet: Planet) -> String {
    let mut buf = [0i8; 256];
    unsafe {
        swe_get_planet_name(planet.to_int(), buf.as_mut_ptr());
        CStr::from_ptr(buf.as_ptr()).to_string_lossy().into_owned()
    }
}

/// Normalize degrees to 0-360 range
pub fn normalize_degrees(deg: f64) -> f64 {
    unsafe { swe_degnorm(deg) }
}

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

    #[test]
    fn test_safe_julday() {
        let jd = julday(2000, 1, 1, 12.0);
        assert!((jd - 2451545.0).abs() < 0.0001);
    }

    #[test]
    fn test_safe_revjul() {
        let (year, month, day, hour) = revjul(2451545.0);
        assert_eq!(year, 2000);
        assert_eq!(month, 1);
        assert_eq!(day, 1);
        assert!((hour - 12.0).abs() < 0.0001);
    }

    #[test]
    fn test_safe_calc() {
        let jd = 2451545.0; // J2000.0
        let flags = CalcFlags::new().with_speed();
        let pos = calc(jd, Planet::Sun, flags).unwrap();
        
        // Sun should be around 280° longitude at J2000.0
        assert!(pos.longitude > 270.0 && pos.longitude < 290.0);
        assert!(pos.latitude.abs() < 1.0);
    }

    #[test]
    fn test_safe_houses() {
        let jd_ut = 2451545.0;
        let cusps = houses(jd_ut, 47.3769, 8.5417, HouseSystem::Placidus).unwrap();
        
        // Ascendant should be a valid degree
        assert!(cusps.ascendant >= 0.0 && cusps.ascendant < 360.0);
        assert!(cusps.mc >= 0.0 && cusps.mc < 360.0);
    }

    #[test]
    fn test_version() {
        let v = version();
        assert!(!v.is_empty());
        // Version should start with a digit
        assert!(v.chars().next().unwrap().is_ascii_digit());
    }
}