1use serde::Serialize;
5use serde_json::{json, Map, Value};
6
7use crate::aspects::{cross_aspects, points_from_json, CrossAspect};
8use crate::catalog::{DERIVED_HOUSE_MEANINGS, ROOT_HOUSE_THEMES};
9use crate::chart::{calculate_chart, ChartRequest, HouseCusp, Placement};
10use crate::ephemeris::KernelSet;
11use crate::error::EngineError;
12use crate::zodiac::ZODIAC_SIGNS;
13
14#[derive(Debug, Clone, PartialEq, Serialize)]
16pub struct TransitChart {
17 pub transit_planets: Vec<Placement>,
19 pub transit_houses: Vec<HouseCusp>,
21 pub cross_aspects: Vec<CrossAspect>,
23 pub transit_datetime: String,
25 pub transit_lat: f64,
27 pub transit_lon: f64,
29 pub zodiac_type: &'static str,
31 pub ayanamsa: Option<&'static str>,
33 pub ayanamsa_name: Option<&'static str>,
35 pub ayanamsa_value: Option<f64>,
37 pub ayanamsa_formatted: Option<String>,
39}
40
41pub fn calculate_transit_chart(
44 kernels: &KernelSet,
45 natal_planets: &Value,
46 req: &ChartRequest,
47) -> Result<TransitChart, EngineError> {
48 let natal = points_from_json(natal_planets)?;
49 let chart = calculate_chart(kernels, req)?;
50 let aspects = cross_aspects(&natal, &chart.points(), req.orb_settings)?;
51 Ok(TransitChart {
52 cross_aspects: aspects,
53 transit_datetime: req.instant.isoformat(),
54 transit_lat: req.latitude,
55 transit_lon: req.longitude,
56 zodiac_type: chart.zodiac_type,
57 ayanamsa: chart.ayanamsa,
58 ayanamsa_name: chart.ayanamsa_name,
59 ayanamsa_value: chart.ayanamsa_value,
60 ayanamsa_formatted: chart.ayanamsa_formatted,
61 transit_planets: chart.planets,
62 transit_houses: chart.houses,
63 })
64}
65
66#[derive(Debug, Clone, PartialEq, Serialize)]
68pub struct Synastry {
69 pub cross_aspects: Vec<CrossAspect>,
71}
72
73pub fn calculate_synastry(
75 chart_a_planets: &Value,
76 chart_b_planets: &Value,
77 orb_settings: Option<&Value>,
78) -> Result<Synastry, EngineError> {
79 let a = points_from_json(chart_a_planets)?;
80 let b = points_from_json(chart_b_planets)?;
81 Ok(Synastry {
82 cross_aspects: cross_aspects(&a, &b, orb_settings)?,
83 })
84}
85
86fn get(obj: &Map<String, Value>, key: &str, default: Value) -> Value {
88 obj.get(key).cloned().unwrap_or(default)
89}
90
91fn truthy(v: Option<&Value>) -> bool {
93 match v {
94 None | Some(Value::Null) => false,
95 Some(Value::Bool(b)) => *b,
96 Some(Value::Number(n)) => n.as_f64() != Some(0.0),
97 Some(Value::String(s)) => !s.is_empty(),
98 Some(Value::Array(a)) => !a.is_empty(),
99 Some(Value::Object(o)) => !o.is_empty(),
100 }
101}
102
103fn house_number_is(h: &Value, n: i64) -> bool {
104 h.get("house_number").and_then(Value::as_f64) == Some(n as f64)
105}
106
107fn turned_house(item: &Map<String, Value>, root: i64) -> (Value, i64) {
109 let radix = get(item, "house", json!(1));
110 let n = radix.as_f64().unwrap_or(1.0) as i64;
111 (radix, (n - root).rem_euclid(12) + 1)
112}
113
114fn turn_items(base: &Map<String, Value>, key: &str, root: i64) -> Result<Vec<Value>, EngineError> {
115 let items = match base.get(key) {
116 None | Some(Value::Null) => return Ok(Vec::new()),
117 Some(Value::Array(items)) => items,
118 Some(other) => {
119 return Err(EngineError::InvalidInput(format!(
120 "{key} must be a list, got {other}"
121 )))
122 }
123 };
124 items
125 .iter()
126 .map(|item| {
127 let mut copy = item.as_object().cloned().ok_or_else(|| {
128 EngineError::InvalidInput(format!("{key} entries must be objects"))
129 })?;
130 let (radix, turned) = turned_house(©, root);
131 copy.insert("radix_house".into(), radix);
132 copy.insert("house".into(), json!(turned));
133 Ok(Value::Object(copy))
134 })
135 .collect()
136}
137
138pub fn calculate_derived_chart(
143 base: &Value,
144 root: i64,
145 custom_name: Option<&str>,
146) -> Result<Value, EngineError> {
147 let base = base
148 .as_object()
149 .ok_or_else(|| EngineError::InvalidInput("base chart must be an object".into()))?;
150 let root = if (1..=12).contains(&root) { root } else { 1 };
151 let meanings = &DERIVED_HOUSE_MEANINGS[root as usize - 1];
152
153 let stored_houses = base
154 .get("houses")
155 .and_then(Value::as_array)
156 .cloned()
157 .unwrap_or_default();
158 let base_houses: Vec<Value> = if stored_houses.len() >= 12 {
159 stored_houses
160 } else {
161 (0..12)
162 .map(|i| {
163 json!({
164 "house_number": i + 1,
165 "degree": i * 30,
166 "minute": 0,
167 "sign": ZODIAC_SIGNS[i].name,
168 "sign_symbol": ZODIAC_SIGNS[i].symbol,
169 "ecliptic_longitude": (i * 30) as f64,
170 })
171 })
172 .collect()
173 };
174 let house_obj = |r: i64| -> Map<String, Value> {
175 base_houses
176 .iter()
177 .find(|h| house_number_is(h, r))
178 .unwrap_or(&base_houses[r as usize - 1])
179 .as_object()
180 .cloned()
181 .unwrap_or_default()
182 };
183
184 let mut derived_houses: Vec<Map<String, Value>> = Vec::with_capacity(12);
185 for d in 1..=12_i64 {
186 let r = (root - 1 + d - 1) % 12 + 1;
187 let radix = house_obj(r);
188 let meaning = meanings[d as usize - 1];
189 let mut h = Map::new();
190 h.insert("house_number".into(), json!(d));
191 h.insert("radix_house_number".into(), json!(r));
192 h.insert("sign".into(), get(&radix, "sign", json!("")));
193 h.insert("sign_symbol".into(), get(&radix, "sign_symbol", json!("")));
194 h.insert("degree".into(), get(&radix, "degree", json!(0)));
195 h.insert("minute".into(), get(&radix, "minute", json!(0)));
196 h.insert(
197 "ecliptic_longitude".into(),
198 get(&radix, "ecliptic_longitude", json!(0.0)),
199 );
200 h.insert(
201 "symbolic_degree".into(),
202 get(&radix, "symbolic_degree", Value::Null),
203 );
204 h.insert(
205 "degree_symbol".into(),
206 get(&radix, "degree_symbol", Value::Null),
207 );
208 h.insert(
209 "degree_symbols".into(),
210 get(&radix, "degree_symbols", Value::Null),
211 );
212 h.insert("meaning_en".into(), json!(meaning.en));
213 h.insert("meaning_it".into(), json!(meaning.it));
214 h.insert(
215 "derived_label".into(),
216 json!(format!("House {d} (Radix {r})")),
217 );
218 derived_houses.push(h);
219 }
220
221 let mut planets = Vec::new();
222 if let Some(Value::Array(items)) = base.get("planets") {
223 for p in items {
224 let mut copy = p.as_object().cloned().ok_or_else(|| {
225 EngineError::InvalidInput("planets entries must be objects".into())
226 })?;
227 let (radix, turned) = turned_house(©, root);
228 copy.insert("radix_house".into(), radix);
229 let angle = match copy.get("name").and_then(Value::as_str) {
230 Some("Ascendant") => Some((0, 1)),
231 Some("Midheaven") => Some((9, 10)),
232 _ => None,
233 };
234 match angle {
235 Some((index, house)) => {
236 let cusp = &derived_houses[index];
237 for key in [
238 "sign",
239 "sign_symbol",
240 "degree",
241 "minute",
242 "ecliptic_longitude",
243 ] {
244 copy.insert(key.into(), cusp[key].clone());
245 }
246 copy.insert("house".into(), json!(house));
247 if truthy(cusp.get("symbolic_degree")) {
248 for key in ["symbolic_degree", "degree_symbol", "degree_symbols"] {
249 copy.insert(key.into(), cusp[key].clone());
250 }
251 }
252 }
253 None => {
254 copy.insert("house".into(), json!(turned));
255 }
256 }
257 planets.push(Value::Object(copy));
258 }
259 }
260 let fixed_stars = turn_items(base, "fixed_stars", root)?;
261 let lots = turn_items(base, "arabic_parts", root)?;
262
263 let (theme_en, theme_it) = ROOT_HOUSE_THEMES[root as usize - 1];
264 let root_cusp = base_houses
265 .iter()
266 .find(|h| house_number_is(h, root))
267 .unwrap_or(&base_houses[0])
268 .as_object()
269 .cloned()
270 .unwrap_or_default();
271 let base_name = match base.get("user_name") {
272 Some(v) if truthy(Some(v)) => v.clone(),
273 _ => json!("Radix Chart"),
274 };
275 let name = match custom_name {
276 Some(n) if !n.is_empty() => n.to_string(),
277 _ => format!(
278 "{} [Derived H{root} - {theme_en}]",
279 base_name
280 .as_str()
281 .map_or_else(|| base_name.to_string(), str::to_string)
282 ),
283 };
284 let meanings_map: Map<String, Value> = meanings
285 .iter()
286 .enumerate()
287 .map(|(i, m)| ((i + 1).to_string(), json!({"en": m.en, "it": m.it})))
288 .collect();
289 let at = |key: &str| root_cusp.get(key).cloned().unwrap_or(Value::Null);
290
291 let derived_data = json!({
292 "derived_root_house": root,
293 "derived_from_id": get(base, "id", Value::Null),
294 "derived_from_name": base_name.clone(),
295 "root_house_theme": {"name_en": theme_en, "name_it": theme_it},
296 "root_cusp": {
297 "house_number": root,
298 "sign": at("sign"),
299 "degree": at("degree"),
300 "minute": at("minute"),
301 "ecliptic_longitude": at("ecliptic_longitude"),
302 },
303 "meanings": meanings_map,
304 });
305
306 let mut out = Map::new();
307 let mut put = |k: &str, v: Value| {
308 out.insert(k.to_string(), v);
309 };
310 put("id", Value::Null);
311 put("chart_type", json!("DERIVED"));
312 put("user_name", json!(name));
313 put("birth_datetime", get(base, "birth_datetime", Value::Null));
314 put("local_datetime", get(base, "local_datetime", Value::Null));
315 put("timezone", get(base, "timezone", json!("UTC")));
316 put(
317 "timezone_offset",
318 get(base, "timezone_offset", json!("+00:00")),
319 );
320 put("timezone_abbr", get(base, "timezone_abbr", json!("UTC")));
321 put("is_dst", get(base, "is_dst", json!(false)));
322 put("dst_offset", get(base, "dst_offset", json!("+00:00")));
323 put("raw_offset", get(base, "raw_offset", json!("+00:00")));
324 put("house_system", get(base, "house_system", json!("P")));
325 put("zodiac_type", get(base, "zodiac_type", json!("tropical")));
326 put(
327 "zodiac_type_label",
328 get(base, "zodiac_type_label", json!("Tropical")),
329 );
330 put("ayanamsa", get(base, "ayanamsa", Value::Null));
331 put("ayanamsa_name", get(base, "ayanamsa_name", Value::Null));
332 put("ayanamsa_value", get(base, "ayanamsa_value", Value::Null));
333 put(
334 "ayanamsa_formatted",
335 get(base, "ayanamsa_formatted", json!("")),
336 );
337 put("orb_settings", get(base, "orb_settings", json!({})));
338 put("coordinates", get(base, "coordinates", json!({})));
339 put("planets", Value::Array(planets));
340 put(
341 "houses",
342 Value::Array(derived_houses.into_iter().map(Value::Object).collect()),
343 );
344 put("aspects", get(base, "aspects", json!([])));
345 put("fixed_stars", Value::Array(fixed_stars));
346 put("arabic_parts", Value::Array(lots));
347 put("temperament", get(base, "temperament", json!({})));
348 put("lunar_status", get(base, "lunar_status", json!({})));
349 put("derived_from_id", get(base, "id", Value::Null));
350 put("derived_from_name", base_name);
351 put("derived_house", json!(root));
352 put("derived_data", derived_data);
353 Ok(Value::Object(out))
354}