"""BUG-2124 (占星师 2026-11-20 第 10 问): the branch of a custom yoga condition that held, in reader words. BUG-2170 (占星师 2026-11-22 裁定 7.2): the record this module reads is the **branch record from the original evaluation** (原执行分支记录; `record_identity` = branch_record_from_original_evaluation). The rule engine runs a custom `and` / `or` expression once, as an instrumented copy that passes each and/or/not operand's value through a recorder in Python's own short-circuit order, and keeps each operand's result with the chart facts it read (`custom_branch_trace`: a list on the yoga row, one record per custom node of the matched instance; the same record also sits on that node's own entry in `condition_evidence`). Each record is bound to the rule id, a rule-content hash, the expression hash and an input snapshot hash. (BUG-2158 had called the earlier, second-run version 同输入的分支复算记录; that second run is gone.) Reader text follows the ruling's 7.3: an operand Python skipped by short-circuit is 「其他分支未执行」 (never 未成立 / 不成立); only operands that were evaluated false are 「未满足」; missing input names the missing condition when the record has it, else 「缺少数据,未判定」; when several branches could have held but only the first ran, only that witness is reported and nothing says it was the only path. A whole-condition, unavailable or missing record says nothing. This module only formats the record. It translates a short whitelist of operand shapes; when any operand on the held path is outside the whitelist, or the record is missing, unsplit or unavailable, it returns "" and the page keeps its current sentence. Raw Python never reaches the reader, and nothing here re-evaluates a rule. """ from __future__ import annotations import ast from typing import Any try: from scripts.report_render.appendix_language import planet_name, sign_name except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path from report_render.appendix_language import planet_name, sign_name PLACEHOLDERS = {"自定义条件满足", "满足自定义条件", "Custom condition met", "custom condition satisfied"} _LORD_CALLS = {"lords_of", "lord", "lord_of_house"} _DIGNITY = { "is_exalted": ("{s}在{sign}入旺", "is exalted"), "exalted": ("{s}在{sign}入旺", "is exalted"), "is_own_sign": ("{s}在自己守护的{sign}", "is in its own sign"), "own": ("{s}在自己守护的{sign}", "is in its own sign"), "is_moolatrikona": ("{s}在根本三方星座{sign}", "is in its moolatrikona sign"), "moola": ("{s}在根本三方星座{sign}", "is in its moolatrikona sign"), "is_debilitated": ("{s}在{sign}落陷", "is debilitated"), "debil": ("{s}在{sign}落陷", "is debilitated"), } _HOUSE_KIND = { "is_kendra": ("角宫(第 1、4、7、10 宫)", "an angular house (1, 4, 7 or 10)"), "kendra": ("角宫(第 1、4、7、10 宫)", "an angular house (1, 4, 7 or 10)"), "is_trikona": ("三方宫(第 1、5、9 宫)", "a trine house (1, 5 or 9)"), "trikona": ("三方宫(第 1、5、9 宫)", "a trine house (1, 5 or 9)"), "is_dusthana": ("凶宫(第 6、8、12 宫)", "a difficult house (6, 8 or 12)"), "dusthana": ("凶宫(第 6、8、12 宫)", "a difficult house (6, 8 or 12)"), } _ZH_COUNT = {1: "一", 2: "两", 3: "三", 4: "四", 5: "五", 6: "六", 7: "七", 8: "八", 9: "九"} _EN_ORDINAL = {1: "1st", 2: "2nd", 3: "3rd"} def _ordinal(n: int) -> str: return _EN_ORDINAL.get(n, f"{n}th") if n not in (11, 12, 13) else f"{n}th" def _call(node: ast.AST, names) -> ast.Call | None: if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in names and len(node.args) == 1 and not node.keywords: return node return None def _int(node: ast.AST) -> int | None: return node.value if isinstance(node, ast.Constant) and type(node.value) is int else None class _Untranslatable(Exception): pass def _subject(node: ast.AST, facts: dict, zh: bool) -> tuple[str, str]: """(reader name, planet key) for 'Venus' or lords_of(7); the planet comes from the run-time facts.""" if isinstance(node, ast.Constant) and isinstance(node.value, str): planet = node.value label = planet_name(planet, "zh" if zh else "en") elif (call := _call(node, _LORD_CALLS)) is not None and (house := _int(call.args[0])) is not None: planet = (facts.get("house_lords") or {}).get(str(house)) if not planet: raise _Untranslatable name = planet_name(planet, "zh" if zh else "en") label = f"第 {house} 宫主{name}" if zh else f"the {_ordinal(house)} lord {name}" else: raise _Untranslatable if planet not in (facts.get("planets") or {}): raise _Untranslatable return label, planet def _place(facts: dict, planet: str, key: str): value = ((facts.get("planets") or {}).get(planet) or {}).get(key) if value in (None, ""): raise _Untranslatable return value def _operand(source: str, facts: dict, zh: bool) -> str | None: """Reader words for one operand that held; None for a data-presence check ('X' in planets).""" try: node = ast.parse(source, mode="eval").body except SyntaxError as exc: raise _Untranslatable from exc if isinstance(node, ast.Compare) and len(node.ops) == 1: op, left, right = node.ops[0], node.left, node.comparators[0] if isinstance(op, ast.In) and isinstance(right, ast.Name) and right.id == "planets": _subject(left, facts, zh) return None if (call := _call(left, {"house_of"})) is not None: label, planet = _subject(call.args[0], facts, zh) house = _place(facts, planet, "house") if isinstance(op, ast.Eq) and _int(right) is not None: return f"{label}在第 {house} 宫" if zh else f"{label} is in house {house}" if isinstance(op, ast.Eq) and (other := _call(right, {"house_of"})) is not None: other_label, other_planet = _subject(other.args[0], facts, zh) if _place(facts, other_planet, "house") != house: raise _Untranslatable return f"{label}与{other_label}同在第 {house} 宫" if zh else f"{label} and {other_label} are both in house {house}" if isinstance(op, ast.In) and isinstance(right, (ast.List, ast.Tuple)): houses = [_int(item) for item in right.elts] if not houses or None in houses: raise _Untranslatable if zh: return f"{label}在第 {house} 宫(第 {'、'.join(str(h) for h in houses)} 宫之一)" listed = ", ".join(str(h) for h in houses[:-1]) + f" or {houses[-1]}" if len(houses) > 1 else str(houses[0]) return f"{label} is in house {house} (one of houses {listed})" raise _Untranslatable if (call := _call(node, set(_DIGNITY))) is not None: label, planet = _subject(call.args[0], facts, zh) sign = sign_name(_place(facts, planet, "sign"), "zh" if zh else "en") words_zh, words_en = _DIGNITY[call.func.id] return words_zh.format(s=label, sign=sign) if zh else f"{label} {words_en} ({sign})" if (call := _call(node, set(_HOUSE_KIND))) is not None and (inner := _call(call.args[0], {"house_of"})) is not None: label, planet = _subject(inner.args[0], facts, zh) house = _place(facts, planet, "house") words_zh, words_en = _HOUSE_KIND[call.func.id] return f"{label}在第 {house} 宫,属{words_zh}" if zh else f"{label} is in house {house}, {words_en}" raise _Untranslatable def _held(node: dict, zh: bool, others: dict) -> list[str]: """Reader words for the operands that held under `node` (result 'true'); collects the other branches by result.""" if node.get("result") != "true": raise _Untranslatable kind = node.get("kind") if kind == "operand": text = _operand(str(node.get("source") or ""), node.get("facts") or {}, zh) return [text] if text else [] children = node.get("children") or [] if kind == "and": return [text for child in children for text in _held(child, zh, others)] if kind == "or": held = [child for child in children if child.get("result") == "true"] if len(held) != 1: raise _Untranslatable for child in children: if child is not held[0]: others.setdefault(child.get("result"), []).append(child) return _held(held[0], zh, others) raise _Untranslatable def held_branch_trace(row: Any) -> dict | None: """The one split, matched custom branch record of a row whose sentence is the placeholder.""" if not isinstance(row, dict) or str(row.get("combination") or "") not in PLACEHOLDERS: return None if isinstance(row.get("custom_branch_trace"), list): records = row["custom_branch_trace"] else: # A row without the top-level key: the matched custom node's own trace entry. evidence = row.get("condition_evidence") trace = evidence.get("execution_trace") if isinstance(evidence, dict) else None records = [ item.get("custom_branch_trace") for item in trace or [] if isinstance(item, dict) and item.get("condition_type") == "custom" and item.get("matched") is True and "custom_branch_trace" in item and "combo_template" not in (item.get("definition") or {}) ] if len(records) != 1 or not isinstance(records[0], dict) or records[0].get("trace_status") != "split": return None return records[0] def _missing_names(node: dict, zh: bool) -> list[str]: """The missing inputs named in an 'unknown' branch: presence checks ('Rahu' in planets) on its operands.""" if node.get("kind") != "operand": return [name for child in node.get("children") or [] if child.get("result") == "unknown" for name in _missing_names(child, zh)] try: parsed = ast.parse(str(node.get("source") or ""), mode="eval").body except SyntaxError: return [] if not (isinstance(parsed, ast.Compare) and len(parsed.ops) == 1 and isinstance(parsed.ops[0], ast.In) and isinstance(parsed.comparators[0], ast.Name) and parsed.comparators[0].id == "planets"): return [] left = parsed.left if isinstance(left, ast.Constant) and isinstance(left.value, str): return [planet_name(left.value, "zh" if zh else "en")] if (call := _call(left, _LORD_CALLS)) is not None and (house := _int(call.args[0])) is not None: planet = ((node.get("facts") or {}).get("house_lords") or {}).get(str(house)) if planet: name = planet_name(planet, "zh" if zh else "en") return [f"第 {house} 宫主{name}" if zh else f"the {_ordinal(house)} lord {name}"] return [] def _unknown_words(node: dict, zh: bool) -> str: names = list(dict.fromkeys(_missing_names(node, zh))) if not names: return "缺少数据,未判定" if zh else "not determined (missing data)" if zh: return f"缺少{'、'.join(names)}的位置数据,未判定" return f"not determined (no position for {', '.join(names)})" def custom_branch_text(row: Any, language: str) -> str: """「第 7 宫主木星在第 10 宫,属角宫(第 1、4、7、10 宫);同一条规则的其他分支:两支未满足」, or "".""" record = held_branch_trace(row) if record is None: return "" zh = language == "zh" others: dict = {} try: parts = _held(record.get("tree") or {}, zh, others) except _Untranslatable: return "" if not parts: return "" if any(key not in ("false", "not_evaluated", "unknown") for key in others): return "" text = ("," if zh else "; ").join(parts) clauses: list[str] = [] if others.get("false"): n = len(others["false"]) clauses.append(f"{_ZH_COUNT.get(n, n)}支未满足" if zh else f"{n} not met") unknown: dict = {} for node in others.get("unknown", []): words = _unknown_words(node, zh) unknown[words] = unknown.get(words, 0) + 1 for words, n in unknown.items(): clauses.append(f"{_ZH_COUNT.get(n, n)}支{words}" if zh else f"{n} {words}") skipped = bool(others.get("not_evaluated")) if zh: if clauses: text += ";同一条规则的其他分支:" + ",".join(clauses) + (",其余分支未执行" if skipped else "") elif skipped: text += ";同一条规则的其他分支未执行" else: if clauses: text += "; other branches of this rule: " + ", ".join(clauses) + (", the rest not evaluated" if skipped else "") elif skipped: text += "; other branches of this rule were not evaluated" return text if zh else text[:1].upper() + text[1:]