use std::sync::Arc; use astro_engine::{AspectSet, Ayanamsa, HouseSystem, LilithType, NodeType, ZodiacType}; use axum::extract::rejection::{JsonRejection, QueryRejection}; use axum::extract::{Query, State}; use axum::http::{HeaderValue, Method}; use axum::routing::{get, post}; use axum::{Json, Router}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use tower_http::cors::{AllowOrigin, Any, CorsLayer}; use tower_http::trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer}; use tracing::Level; use crate::AppState; use crate::error::ApiError; use crate::natal::{self, NatalRequest, NatalResponse}; use crate::synastry::{self, SynastryRequest, SynastryResponse}; type AppResult = Result, ApiError>; pub fn router(state: Arc) -> Router { Router::new() .route("/healthz", get(health)) .route("/v1/info", get(info)) .route("/v1/countries", get(countries)) .route("/v1/places", get(places)) .route("/v1/timezones", get(timezones)) .route("/v1/natal", post(natal_chart)) .route("/v1/synastry", post(synastry_chart)) .layer(cors()) .layer( TraceLayer::new_for_http() .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) .on_response(DefaultOnResponse::new().level(Level::INFO)), ) .with_state(state) } fn cors() -> CorsLayer { let origins = std::env::var("CORS_ALLOWED_ORIGINS").unwrap_or_else(|_| "*".into()); let allow = if origins.trim() == "*" { AllowOrigin::any() } else { AllowOrigin::list(origins.split(',').filter_map(|o| HeaderValue::from_str(o.trim()).ok())) }; CorsLayer::new().allow_origin(allow).allow_methods([Method::GET, Method::POST]).allow_headers(Any) } async fn health() -> Json { Json(json!({ "status": "ok" })) } async fn info(State(state): State>) -> Json { Json(json!({ "meta": natal::meta(&state), "places_loaded": state.atlas.places.len(), "options": { "house_system": HouseSystem::ALL, "zodiac": [ZodiacType::Tropical, ZodiacType::Sidereal], "ayanamsa": [ Ayanamsa::Lahiri, Ayanamsa::FaganBradley, Ayanamsa::Raman, Ayanamsa::Krishnamurti, Ayanamsa::DeLuce, Ayanamsa::Yukteshwar, Ayanamsa::TrueCitra, Ayanamsa::GalacticCenter0Sag, ], "node_type": [NodeType::True, NodeType::Mean], "lilith_type": [LilithType::Mean, LilithType::True], "aspect_set": [AspectSet::Major, AspectSet::Extended], "ambiguous_time": ["reject", "earlier", "later"], "calendar": ["gregorian", "julian"], }, "defaults": astro_engine::ChartOptions::default(), })) } #[derive(Serialize)] struct CountryEntry<'a> { #[serde(flatten)] country: &'a geo_tz::Country, timezones: Vec<&'a str>, } async fn countries(State(state): State>) -> Json { let list: Vec = state .atlas .places .countries() .iter() .map(|c| CountryEntry { country: c, timezones: state.atlas.zones.zones_of(&c.iso2).iter().map(|z| z.name.as_str()).collect(), }) .collect(); Json(json!({ "countries": list })) } #[derive(Deserialize)] struct PlacesQuery { country: String, q: String, region: Option, limit: Option, } async fn places( State(state): State>, query: Result, QueryRejection>, ) -> AppResult { let Query(q) = query?; let country = state.atlas.places.country(&q.country)?; let limit = q.limit.unwrap_or(10).clamp(1, 50); let matches = state.atlas.places.search(country, &q.q, q.region.as_deref(), limit); Ok(Json(json!({ "country": country, "query": q.q, "places": matches }))) } #[derive(Deserialize)] struct TimezonesQuery { country: String, } async fn timezones( State(state): State>, query: Result, QueryRejection>, ) -> AppResult { let Query(q) = query?; let country = state.atlas.places.country(&q.country)?; Ok(Json(json!({ "country": country, "tzdb_version": state.atlas.zones.version, "timezones": state.atlas.zones.zones_of(&country.iso2), }))) } async fn natal_chart( State(state): State>, body: Result, JsonRejection>, ) -> AppResult { let Json(request) = body?; // The ephemeris engine serializes access internally; keep it off the async workers. let response = tokio::task::spawn_blocking(move || { natal::calculate(&state, request).map(|result| NatalResponse { result, meta: natal::meta(&state) }) }) .await .map_err(|e| ApiError::Internal(e.to_string()))??; Ok(Json(response)) } async fn synastry_chart( State(state): State>, body: Result, JsonRejection>, ) -> AppResult { let Json(request) = body?; let response = tokio::task::spawn_blocking(move || synastry::calculate(&state, request)) .await .map_err(|e| ApiError::Internal(e.to_string()))??; Ok(Json(response)) }