"""VedAstro response echo check and key handling (BUG-2172, issue #327). The VedAstro API answers ``Status: Pass`` even when it ignored the request and computed its own sample chart (2026-11-22, every request shape we tried came back as 14:30 25/10/1992 Mumbai, Ayanamsa 3). A ``Pass`` therefore only counts when the ``Input`` the API echoes back carries the same time and place we sent, and, when we asked for one, the same ayanamsa. Anything else is reported as ``input_echo_mismatch`` and must be treated as a failure: not cached, never used to build an official chart. The API key comes only from the ``VEDASTRO_API_KEY`` environment variable. It is sent in the ``x-api-key`` header (REST paths) or set with ``Calculate.SetAPIKey`` (official SDK path). It is never returned, logged or put into a cache key by this module. """ from __future__ import annotations import json import os from typing import Any, Iterable API_KEY_ENV = "VEDASTRO_API_KEY" API_KEY_HEADER = "x-api-key" ECHO_MISMATCH = "input_echo_mismatch" _COORD_TOLERANCE = 0.01 # vedastro.Ayanamsa enum values (SDK 1.23.25, vedastro/vedastro.py). AYANAMSA_CODES: dict[str, int] = { "fagan_bradley": 0, "lahiri": 1, "deluce": 2, "raman": 3, "ushashashi": 4, "krishnamurti": 5, "kp": 5, "djwhal_khul": 6, "yukteshwar": 7, "jn_bhasin": 8, } def api_key() -> str: return os.environ.get(API_KEY_ENV, "").strip() def with_api_key_header(headers: dict[str, str] | None = None) -> dict[str, str]: """Return a copy of ``headers`` carrying the key when one is configured.""" merged = dict(headers or {}) key = api_key() if key: merged[API_KEY_HEADER] = key return merged def _time_objects(value: Any) -> Iterable[dict[str, Any]]: """Yield every ``{StdTime, Location}`` object nested in a request or echo.""" if isinstance(value, dict): if isinstance(value.get("StdTime"), str): yield value for item in value.values(): yield from _time_objects(item) elif isinstance(value, list): for item in value: yield from _time_objects(item) def _signature(time_object: dict[str, Any]) -> tuple[str, float | None, float | None]: location = time_object.get("Location") if isinstance(time_object.get("Location"), dict) else {} def _num(key: str) -> float | None: try: return float(location.get(key)) except (TypeError, ValueError): return None return (" ".join(str(time_object.get("StdTime") or "").split()), _num("Latitude"), _num("Longitude")) def _same_place(a: float | None, b: float | None) -> bool: return a is not None and b is not None and abs(a - b) <= _COORD_TOLERANCE def ayanamsa_code(raw: Any) -> int | None: if raw is None or isinstance(raw, bool): return None if isinstance(raw, int): return raw return AYANAMSA_CODES.get(str(raw).strip().lower().replace(" ", "_").replace("-", "_")) def _requested_ayanamsa(request_body: Any, expected_ayanamsa: Any = None) -> int | None: explicit = ayanamsa_code(expected_ayanamsa) if explicit is not None: return explicit if isinstance(request_body, dict): for key in ("Ayanamsa", "ayanamsa"): if key in request_body: return ayanamsa_code(request_body[key]) return None def echo_mismatch_reason(request_body: Any, response: Any, expected_ayanamsa: Any = None) -> str | None: """Return why a ``Pass`` response does not answer our request, or ``None``. Only ``Status: Pass`` responses are judged; failures are already failures. """ if not isinstance(response, dict) or str(response.get("Status") or "") != "Pass": return None sent = [_signature(item) for item in _time_objects(request_body)] if not sent: return None echoed_input = response.get("Input") if isinstance(echoed_input, str): try: echoed_input = json.loads(echoed_input) except ValueError: return "echo_input_not_structured" if not isinstance(echoed_input, dict): return "echo_input_missing" echoed = [_signature(item) for item in _time_objects(echoed_input)] if not echoed: return "echo_time_missing" for std_time, lat, lon in sent: if not any( std_time == e_time and _same_place(lat, e_lat) and _same_place(lon, e_lon) for e_time, e_lat, e_lon in echoed ): return "echo_time_or_place_differs" wanted = _requested_ayanamsa(request_body, expected_ayanamsa) if wanted is not None: got = echoed_input.get("Ayanamsa") try: if int(got) != wanted: return "echo_ayanamsa_differs" except (TypeError, ValueError): return "echo_ayanamsa_missing" return None def guard_response(request_body: Any, response: Any, expected_ayanamsa: Any = None) -> Any: """Turn a ``Pass`` that answers someone else's chart into a failure.""" reason = echo_mismatch_reason(request_body, response, expected_ayanamsa) if reason is None: return response return { "Status": "Fail", "Payload": {"reason": ECHO_MISMATCH, "detail": reason}, "echo_check": {"status": ECHO_MISMATCH, "detail": reason}, } def install_sdk_guard(module: Any) -> None: """Make the official SDK send the key and refuse sample-chart answers. The SDK's ``Calculate._make_request`` drops the echoed ``Input``, so the check has to happen inside the request itself. The replacement keeps the SDK's own contract (raise on Fail, return the Payload) and additionally raises when the echo does not match what was sent. """ calculate = getattr(module, "Calculate", None) if calculate is None or getattr(calculate, "_jyotisha_echo_guard", False): return key = api_key() if key and hasattr(calculate, "SetAPIKey"): calculate.SetAPIKey(key) import requests # the SDK's own dependency def _make_request(cls: Any, endpoint: str, params: dict[str, Any]) -> Any: url = f"{cls.base_url}/{endpoint}" body = dict(params) headers = {"Content-Type": "application/json"} if cls.api_key: body["APIKey"] = cls.api_key headers[API_KEY_HEADER] = cls.api_key response = requests.post(url, json=body, headers=headers, timeout=120) response.raise_for_status() data = response.json() if data.get("Status") == "Fail": raise RuntimeError(f"VedAstro API error: {data.get('Payload', 'Unknown error')}") reason = echo_mismatch_reason(params, data) if reason is not None: raise RuntimeError(f"VedAstro API error: {ECHO_MISMATCH} ({reason})") payload = data.get("Payload") if not payload: raise ValueError("Payload is missing or empty in API response") if isinstance(payload, list): return payload if isinstance(payload, dict): values = list(payload.values()) return values[0] if len(values) == 1 else payload return payload calculate._make_request = classmethod(_make_request) calculate._jyotisha_echo_guard = True