"""Public professional-reference export assembly for the Jyotish API. This boundary performs no writing-agent, persistence, billing, or telemetry work. It validates the public export request, reuses the handler's one full-reading calculation, and delegates packet assembly/rendering to ``jyotish_engine``. """ from __future__ import annotations import copy import os import sys import time from datetime import datetime from importlib import import_module from types import SimpleNamespace from typing import Any try: from scripts.pl9_full_data_export import ( FULL_DATA_EDITION, REPORT_VERSION_FULL, render_full_data_markdown, ) from scripts.reader_appendix_language import clean_reader_appendix_markdown from scripts.reader_dasha_applicability import render_dasha_applicability from scripts.report_density_packet import report_density_packet from scripts.report_render.birth_precision_window import report_birth_window from scripts.report_render.yoga_status_words import report_yoga_conditions except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path from pl9_full_data_export import ( FULL_DATA_EDITION, REPORT_VERSION_FULL, render_full_data_markdown, ) from reader_appendix_language import clean_reader_appendix_markdown from reader_dasha_applicability import render_dasha_applicability from report_density_packet import report_density_packet from report_render.birth_precision_window import report_birth_window from report_render.yoga_status_words import report_yoga_conditions try: from scripts.report_perf_flags import report_reference_cache_enabled except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path from report_perf_flags import report_reference_cache_enabled class ProfessionalReportReferenceInputError(ValueError): """The professional-reference request is outside the public contract.""" REFERENCE_EDITION = "reference" def _normalize_edition(value: Any) -> str: if value is None or value == "": return REFERENCE_EDITION if not isinstance(value, str): raise ProfessionalReportReferenceInputError("edition must be a string") normalized = value.strip() if normalized in {"", REFERENCE_EDITION, "professional_reference"}: return REFERENCE_EDITION if normalized == "reader_main": raise ProfessionalReportReferenceInputError("edition reader_main has been removed; use full_data") if normalized == FULL_DATA_EDITION: return FULL_DATA_EDITION raise ProfessionalReportReferenceInputError("edition must be reference or full_data") def _normalize_format(value: Any) -> str: if value is None: return "json" if not isinstance(value, str): raise ProfessionalReportReferenceInputError("format must be json or markdown") normalized = value.strip().lower() if normalized not in {"json", "markdown"}: raise ProfessionalReportReferenceInputError("format must be json or markdown") return normalized def _normalize_packs(value: Any) -> list[str]: if value is None: return [] if isinstance(value, str): raw_items = value.split(",") elif isinstance(value, list): if any(not isinstance(item, str) for item in value): raise ProfessionalReportReferenceInputError("packs must contain only strings") raw_items = value else: raise ProfessionalReportReferenceInputError("packs must be a string or array of strings") selected: list[str] = [] seen: set[str] = set() for item in raw_items: pack_id = item.strip() if pack_id and pack_id not in seen: selected.append(pack_id) seen.add(pack_id) return selected def _normalize_languages(value: Any) -> list[str]: """``languages`` is optional; only ``zh`` and ``en`` exist. Absent means today's zh-only reply.""" if value is None: return [] if not isinstance(value, list) or any(not isinstance(item, str) for item in value): raise ProfessionalReportReferenceInputError("languages must be an array of strings") selected = [] for item in value: language = item.strip().lower() if language not in {"zh", "en"}: raise ProfessionalReportReferenceInputError("languages may contain only zh and en") if language not in selected: selected.append(language) return selected def _with_report_tajika_view(packet: dict) -> dict: """Read Tajika named yogas from their own field in the full-data report. The shared annual pack keeps `tajika_yogas` as the candidate list the chat annual card uses; only this report copy swaps in `tajika_named_yogas`. """ worksheets = packet.get("worksheets") timing = worksheets.get("timing_and_predictive_systems") if isinstance(worksheets, dict) else None annual = timing.get("annual_tajika_pack") if isinstance(timing, dict) else None named = annual.get("tajika_named_yogas") if isinstance(annual, dict) else None if not isinstance(named, dict) or named.get("status") == "not_applicable": return packet packet["worksheets"] = {**worksheets, "timing_and_predictive_systems": { **timing, "annual_tajika_pack": {**annual, "tajika_yogas": named}}} return packet def _english_edition(packet: dict, include_fact_tables: bool) -> dict[str, Any]: """Render the English reader from a deep copy of the same packet. The English edition is secondary: any failure, or any Chinese character left in it, drops it and reports why. The Chinese edition is never touched. """ try: from scripts.pl9_reader_english import HAN, _public_wording_en except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path from pl9_reader_english import HAN, _public_wording_en try: english = copy.deepcopy(packet) english["report_language"] = "en" markdown = render_full_data_markdown(english) applicability = ( _public_wording_en(render_dasha_applicability(copy.deepcopy(packet), language="en")) if include_fact_tables else None ) except Exception: # noqa: BLE001 - the English edition must never fail the Chinese one return {"english_unavailable": "render_error"} if not isinstance(markdown, str) or not markdown.strip(): return {"english_unavailable": "empty"} if HAN.search(markdown) or (applicability is not None and HAN.search(applicability)): return {"english_unavailable": "han_leak"} return { "markdown_en": markdown, **({"reader_dasha_applicability_en": applicability} if applicability is not None else {}), } def _load_engine(): try: return import_module("scripts.jyotish_engine") except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path return import_module("jyotish_engine") def _export_args(birth: dict[str, Any]) -> SimpleNamespace: today = birth.get("today") or datetime.now().strftime("%Y-%m-%d") raw_target = birth.get("target_year") if raw_target in (None, ""): target_year = int(str(today)[:4]) else: target_year = int(raw_target) raw_age = birth.get("age") if raw_age in (None, ""): try: age = int(target_year) - int(birth["year"]) except (TypeError, ValueError, KeyError): age = None else: age = int(raw_age) payload = { **birth, "hour": int(birth["hour"]), "minute": int(birth["minute"]), "second": int(birth.get("second", 0) or 0), "today": today, "target_year": target_year, "age": age, "visual_chart_observations": birth.get("visual_chart_observations"), "startrack_language_bridge": bool(birth.get("startrack_language_bridge")), } gender = birth.get("gender") if gender in ("female", "male"): if payload["startrack_language_bridge"]: payload["startrack_gender"] = gender if payload.get("chara_profile") == "goel_gendered": payload["chara_gender"] = gender return SimpleNamespace(**payload) def _reading_facts(packet: dict, full_reading: dict, minute_confirmed: bool, today: str | None, **mode: Any) -> dict[str, Any]: """Facts for the model-written reading (issue #113 R1). Never fails the report.""" try: try: from scripts.report_render.reading_facts import build_report_reading_facts except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path from report_render.reading_facts import build_report_reading_facts return build_report_reading_facts(packet, full_reading, minute_confirmed=minute_confirmed, today=today, **mode) except Exception as exc: # noqa: BLE001 - the reading is optional, the report is not return {"schema": "report-reading-facts-v1", "gaps": ["reading_facts_unavailable"], "error_type": type(exc).__name__} def _load_report_cache(): try: from scripts import consult_full_data_cache as cache except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path import consult_full_data_cache as cache return cache def _narayana_profile_config() -> dict[str, str]: try: import narayana_rath as nr except ModuleNotFoundError: # pragma: no cover - package import from scripts import narayana_rath as nr return dict(nr.DEFAULT_STEP_PROFILES) def _report_cache_sha() -> str: return os.environ.get("GITHUB_SHA") or "" def _report_cache_identity( birth: dict[str, Any], output_format: str, edition: str, packs: list[str], languages: list[str], include_fact_tables: bool, sha: str, reading: dict[str, Any] | None = None, birth_window: dict[str, Any] | None = None, ) -> dict[str, Any]: return { "birth": birth, "format": output_format, "edition": edition, "packs": list(packs), "languages": list(languages), "include_fact_tables": include_fact_tables, "report_version": REPORT_VERSION_FULL, "github_sha": sha, # 占星师 2026-11-08 第六轮 R1:缓存键含 Narayana 全套 profile 与算法版本(不只靠 commit)。 "narayana_profile_config": _narayana_profile_config(), "include_reading_facts": reading is not None, **({"birth_window": birth_window} if birth_window is not None else {}), **({"reading": reading} if reading is not None else {}), } def _assemble_professional_report_reference( handler, birth: dict[str, Any], output_format: str, edition: str, packs: list[str], languages: list[str], include_fact_tables: bool, engine, reading: dict[str, Any] | None = None, birth_window: dict[str, Any] | None = None, ) -> dict[str, Any]: args = _export_args(birth) engine_context = {key: value for key, value in vars(args).items() if key in ("gender", "chara_profile", "chara_gender")} full_reading = handler._compute_full_reading_for_thematic( birth, **({"engine_context": engine_context} if engine_context else {}), ) resolved_engine = engine or _load_engine() try: packet = resolved_engine.build_professional_report_reference_packet( full_reading, args, packs, include_annual_method_reference=edition == FULL_DATA_EDITION, ) except ValueError as exc: raise ProfessionalReportReferenceInputError(str(exc)) from exc if edition == FULL_DATA_EDITION and isinstance(packet, dict): packet = _with_report_tajika_view(dict(packet)) packet["report_version"] = REPORT_VERSION_FULL if output_format == "markdown": if edition == FULL_DATA_EDITION: if birth_window is not None: packet["report_birth_window"] = birth_window if "gender" in birth: # Prime the report's shared yoga projection before either edition renders. report_yoga_conditions(packet, gender=birth["gender"]) # English renders from its own deep copy first, so nothing the Chinese # renderer does to the packet can reach it (and vice versa). english = _english_edition(packet, include_fact_tables) if "en" in languages else {} markdown = render_full_data_markdown(packet) else: markdown = resolved_engine.render_pl9_markdown(packet) return { "format": "markdown", "edition": edition, "report_version": REPORT_VERSION_FULL if edition == FULL_DATA_EDITION else packet.get("report_version"), "markdown": markdown, **({"fact_table_packet": report_density_packet(packet), "reader_dasha_applicability": clean_reader_appendix_markdown(render_dasha_applicability(packet))} if include_fact_tables else {}), **(english if edition == FULL_DATA_EDITION and "en" in languages else {}), **({"reading_facts": _reading_facts( packet, full_reading, gender=birth.get("gender"), **reading, )} if reading is not None and edition == FULL_DATA_EDITION else {}), } return { "format": "json", "edition": edition, "report": packet, } def _report_window_options(body: dict[str, Any]) -> dict[str, Any]: try: from scripts.consult_card_domain_facts import minute_confirmed_from_body except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path from consult_card_domain_facts import minute_confirmed_from_body minute_confirmed = minute_confirmed_from_body(body) and body.get("reading_minute_confirmed") is not False window = body.get("birth_time_window") if window is None and body.get("birth_time_uncertainty_known") is not False: window = {"before_minutes": body.get("uncertainty_before_minutes"), "after_minutes": body.get("uncertainty_after_minutes"), "source": "user_stated"} return { "minute_confirmed": minute_confirmed, "birth_time_window": report_birth_window(window, minute_confirmed=minute_confirmed), } def _reading_request(body: dict[str, Any], window_options: dict[str, Any] | None = None) -> dict[str, Any] | None: """`include_reading_facts: true` asks for the reading facts; off by default.""" if body.get("include_reading_facts") is not True: return None today = body.get("today") return { **(window_options if window_options is not None else _report_window_options(body)), "today": today if isinstance(today, str) else None, **{key: body[key] for key in ("report_mode", "subject_life_status") if key in body}, } def build_professional_report_reference(handler, body: dict[str, Any], *, engine=None) -> dict[str, Any]: """Build one JSON or Markdown response from one reused full-reading result.""" if not isinstance(body, dict): raise ProfessionalReportReferenceInputError("request body must be an object") output_format = _normalize_format(body.get("format")) edition = _normalize_edition(body.get("edition")) packs = _normalize_packs(body.get("packs")) languages = _normalize_languages(body.get("languages")) if languages and (output_format != "markdown" or edition != FULL_DATA_EDITION): raise ProfessionalReportReferenceInputError("languages requires format markdown and edition full_data") birth = handler._high_rigor_birth_payload(body) if body.get("gender") in ("female", "male"): birth["gender"] = body["gender"] include_fact_tables = body.get("include_fact_tables") is True window_options = _report_window_options(body) if edition == FULL_DATA_EDITION and output_format == "markdown" else None reading = _reading_request(body, window_options) if window_options is not None else None birth_window = window_options["birth_time_window"] if window_options is not None else None sha = _report_cache_sha() use_cache = ( report_reference_cache_enabled() and output_format == "markdown" and edition == FULL_DATA_EDITION and sha not in ("", "unknown") ) if not use_cache: return _assemble_professional_report_reference( handler, birth, output_format, edition, packs, languages, include_fact_tables, engine, reading, birth_window, ) identity = _report_cache_identity( birth, output_format, edition, packs, languages, include_fact_tables, sha, reading, birth_window, ) started = time.perf_counter() def builder(_identity: dict[str, Any]) -> dict[str, Any]: return _assemble_professional_report_reference( handler, birth, output_format, edition, packs, languages, include_fact_tables, engine, reading, birth_window, ) cached = _load_report_cache().get_or_build( identity, builder, cache_name="report_reference_cache", json_default=str, ) elapsed_ms = int(round((time.perf_counter() - started) * 1000)) state = "hit" if cached["hit"] else "miss" print(f"[report-reference-cache] {state} elapsed_ms={elapsed_ms}", file=sys.stderr) return cached["packet"]