#!/usr/bin/env python3
"""
Witness 3 (w3_zodiac_bath_rules):
Extract and verify explicit zodiac / Moon-in-sign / mansion / month -> bathing
execution rules from local comparators and /manuscripts, build a 12-sign
cross-witness bathing matrix (Aries-Pisces, preserving Q-M15), and cross-check
against MS 408 Join 3 intersections without conflating historical rules with
MS 408 claims.

Strictly read-only on all external sources and SQLite databases.
Writes only inside ../../../resources/tools/provenance/index.html#s-0c2d6426823535ac
"""

import csv
import hashlib
import json
import os
import re
import sqlite3
from datetime import datetime, timezone
from pathlib import Path

OUT_DIR = Path("../../../resources/tools/provenance/index.html#s-660b09f70bffa6d6")
SUBSTRATE_DB = Path("../../../resources/tools/substrate/index.html")
JOIN3_REG = Path("67e3d39bbc4b78a009bc180b.json")
CGM7958_TSV = Path("efab4fcc99e45a1be5f1b1d4.tsv")
WELLCOME_CAT = Path("../../../resources/readers/collection/voynich/wellcome_mss_pre1650_catalogue_djvu.txt")
ZODIAC_USES_JSON = Path("cb7449e9c540c4bbb08c6e25.json")
IF35_GAP2_MD = Path("../../../resources/tools/provenance/index.html#s-8427725bda1c7721")
HAUSBUSH_SELECTED_MD = Path("5a1206d3a2c4922c3c9e1baa.md")
HAUSBUSH_ACCEPTED_JSON = Path("d23573606894bb2be346be66.json")
CPG557_REF_MD = Path("../../../resources/readers/collection/manuscripts/Heidelberg_Cpg_557/REFERENCE.source.html")
CPG213_REF_MD = Path("../../../resources/readers/collection/manuscripts/Heidelberg_Cpg_213/REFERENCE.source.html")

SIGNS_12 = [
    "Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
    "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"
]


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def verify_source_paths(paths: list[str]) -> dict[str, dict]:
    out = {}
    for p_str in paths:
        p = Path(p_str)
        exists = p.exists()
        if not exists:
            raise FileNotFoundError(f"Cited source path missing: {p_str}")
        out[p_str] = {
            "exists": True,
            "is_dir": p.is_dir(),
            "bytes": p.stat().st_size if p.is_file() else None,
        }
    return out


def load_cgm7958_water_and_m15() -> dict:
    """Parse CGM7958_28_MANSION_TRANSLATION_TABLE.tsv and verify Q-M15 alignment."""
    rows = []
    with open(CGM7958_TSV, "r", encoding="utf-8") as f:
        reader = csv.DictReader(f, delimiter="\t")
        for r in reader:
            rows.append(r)

    m15 = next(r for r in rows if r["mansion_number"].strip() == "15")
    # Verify Q-M15 structural field shift directly from TSV cells
    q_m15_verified = {
        "mansion_number": 15,
        "mansion_name_source_form": m15["mansion_name_source_form"],
        "mansion_name_normalized": m15["mansion_name_normalized"],
        "folio": m15["folio"],
        "source_text_verbatim": m15["source_text"],
        "tsv_body_profile": m15["body_profile"],
        "tsv_predisposition_actually_holds_marks": m15["predisposition"],
        "tsv_diagnostic_marks_actually_holds_water_and_age_risk": m15["diagnostic_marks"],
        "tsv_likely_death_or_risk": m15["likely_death_or_risk"],
        "unverified_hypothesis_columns_excluded": {
            "treatment_implication": m15["treatment_implication"],
            "herbal_crossref_candidate": m15["herbal_crossref_candidate"],
            "balneal_crossref_candidate": m15["balneal_crossref_candidate"],
        },
        "q_m15_qualifier": (
            "CRITICAL Q-M15 FIELD-ALIGNMENT QUALIFIER: In CGM7958_28_MANSION_TRANSLATION_TABLE.tsv row M15 "
            "(Algofara / Al-Ghafr, fol. 6v-7r), bodily diagnostic marks ('pei dem gemächt ij zairen', etc.) "
            "occupy the `predisposition` column, while the water/age risk ('sal sich hüten vor wassen; ill at 38; "
            "ill at 40; dies') occupies the `diagnostic_marks` column and `likely_death_or_risk` says '[pending]'. "
            "Furthermore, `treatment_implication`, `herbal_crossref_candidate`, and `balneal_crossref_candidate` "
            "(e.g., Zone 2 bath / f79r pipe-delivery) are unverified modern hypotheses, NOT historical Cgm 7958 rules. "
            "Historically, Cgm 7958 fol. 6v-7r is a nativity prognostic ('wer dar under geporn...' implied in the series), "
            "NOT an electional Moon-in-mansion bathing instruction."
        ),
    }

    water_mansions = []
    for r in rows:
        st = r.get("source_text", "")
        tr = r.get("translation", "")
        dr = r.get("likely_death_or_risk", "")
        dm = r.get("diagnostic_marks", "")
        if re.search(r"wassen|wasser|wasin", st, re.I) or re.search(r"water", dr + " " + dm, re.I):
            water_mansions.append({
                "mansion_number": int(r["mansion_number"]),
                "name_source": r["mansion_name_source_form"],
                "name_normalized": r["mansion_name_normalized"],
                "folio": r["folio"],
                "source_text_excerpt_match": re.findall(r"[^—\n]{0,60}(?:wassen|wasser|wasin)[^—\n]{0,60}", st, re.I),
                "source_text_full": st,
                "historical_kind": "Nativity life-risk / death warning ('wer dar under geporn wirt'), NOT bathing election",
            })

    return {
        "total_mansions_in_tsv": len(rows),
        "m15_q_m15_record": q_m15_verified,
        "all_water_mentioning_mansions": water_mansions,
    }


def load_wellcome549_catalog() -> dict:
    text = WELLCOME_CAT.read_text(encoding="utf-8", errors="replace")
    m = re.search(r"(549\.\s*MISCELLANEA\s+Medica\s+XXIII.*?86v?\s+Table of zodiacal signs.*?\n)", text, re.S)
    m2 = re.search(r"86[\"v]?\s+Table of zodiacal signs[^\n]*(?:\n[^\n]{0,80})*", text)
    snippet = m2.group(0).replace("\n", " ").strip() if m2 else ""
    hdr = re.search(r"549\.\s*MISCELLANEA Medica XXIII\.[^\n]*(?:\n[^\n]*){0,4}", text)
    hdr_str = hdr.group(0).replace("\n", " ").strip() if hdr else ""
    return {
        "header_excerpt": hdr_str,
        "f86v_excerpt": snippet,
    }


def load_substrate_metadata() -> dict:
    conn = sqlite3.connect(f"file:{SUBSTRATE_DB}?mode=ro", uri=True)
    cur = conn.cursor()
    shelf_queries = [76, 84, 97, 105, 108, 109, 145, 465, 466, 467, 502, 538, 590, 641, 678, 715, 733, 744, 745, 807]
    mss = {}
    for mid in shelf_queries:
        row = cur.execute(
            "SELECT id, shelfmark, title, status, date, language FROM manuscripts WHERE id=?",
            (mid,),
        ).fetchone()
        if row:
            mss[str(mid)] = {
                "id": row[0],
                "shelfmark": row[1],
                "title": row[2],
                "status": row[3],
                "date": row[4],
                "language": row[5],
            }
    conn.close()
    return mss


def load_if35_grid() -> dict:
    with open(ZODIAC_USES_JSON, "r", encoding="utf-8") as f:
        zu = json.load(f)
    baln_row = [r for r in zu["if35_grid_rows"] if "Balneari" in r.get("reading", "")]
    gap2_txt = IF35_GAP2_MD.read_text(encoding="utf-8")
    m_row = re.search(r'Row label "Balneari":\s*([Bmo ]+)\.', gap2_txt)
    grades = m_row.group(1).split() if m_row else []
    assert len(grades) == 12, f"Expected 12 Balneari grid grades, got {grades}"
    return {
        "row_meta": baln_row[0],
        "sign_grades": dict(zip(SIGNS_12, grades)),
        "note": "Grid row f22v pos 26 ('Balneari'); B=good, m=middle, o=bad (retained normalization).",
    }


def load_join3_summary() -> dict:
    with open(JOIN3_REG, "r", encoding="utf-8") as f:
        reg = json.load(f)

    panels_by_folio = {p["folio"]: p for p in reg["task1_pixel_polar_registration"]["panels"]}
    cons_by_folio = {c["folio"]: c for c in reg["task2_whole_panel_and_controls"]["whole_panel_consistency"]}
    per_face = {x["folio"]: x for x in reg["task3_quire13_zodiac_audit"]["quire13_per_face"]}
    macro = reg["task3_quire13_zodiac_audit"]["macro_timing_intersections"]
    pigm = reg["task3_quire13_zodiac_audit"]["quire13_pigment_measurements"]

    return {
        "f71v_light_taurus": {
            "consistency": cons_by_folio["f71v"],
            "shared_anchors": reg["task3_quire13_zodiac_audit"]["zodiac_shared_anchors"]["f71v"],
            "f83v_P3_overlap": next(x for x in macro["complete_context_overlaps"] if x["receiving_context"] == "bath_f83v.P3"),
            "f88v_P2_overlap": next(x for x in macro["complete_context_overlaps"] if x["receiving_context"] == "store_f88v.P2"),
            "whole_group_census": macro["whole_group_census"],
        },
        "f72v2_virgo": {
            "consistency": cons_by_folio["f72v2"],
            "chip_contiguous_intersection": macro["chip_contiguous_intersections"],
            "virgo_suffix_control": macro["virgo_suffix_control"],
        },
        "f71r_pale_aries": {
            "registration": panels_by_folio["f71r"],
            "consistency": cons_by_folio["f71r"],
        },
        "f83v_quire13": {
            "per_face": per_face["f83v"],
            "quire13_20face_summary": reg["task3_quire13_zodiac_audit"]["quire13_20face_summary"],
            "pigments": pigm["f83v"],
        },
        "f75v_quire13": {
            "per_face": per_face["f75v"],
            "pigments": pigm["f75v"],
        },
    }


def build_rules_catalog(cgm7958_data: dict, w549_cat: dict, if35_grid: dict) -> list[dict]:
    """
    Build the full verified catalog of explicit zodiac / Moon-in-sign / mansion /
    month / season / phase -> bathing execution rules on disk.
    """
    rules = [
        # --- 1. MOON-IN-SIGN BATHING RULES (EXPLICIT) ---
        {
            "rule_id": "R-CPG213-155R-FAV",
            "witness_shelfmark": "Heidelberg, UB, Cod. Pal. germ. 213",
            "manuscript_date_place": "1421 colophon (Fascicle II, f171r); East Franconian / Bavarian",
            "folio_locus": "f155r (Regel der Gesundheit, ch. 22: Eyn capitel vom Baden)",
            "rule_type": "MOON_IN_SIGN_BATH",
            "input_condition": "Moon in Aries, Scorpio, Pisces, Sagittarius, Taurus, Libra, or Cancer (plus Moon waning for bathing/cupping)",
            "gate": "FAVORABLE",
            "bath_parameter": "Bathing in general (following sweat-bath vs water-bath distinction; Moon waning required for bathing/cupping)",
            "signs_covered": ["Aries", "Scorpio", "Pisces", "Sagittarius", "Taurus", "Libra", "Cancer"],
            "verbatim_excerpt": "Wenne man baden wil oder schrepffen so sol der monde syn yn den abneme ... Wer baden wil der sol baden so der monde ist in dem wyder oder yn dem storpion [scorpion] oder in dem vyshe oder yn sagittario in dem sützen oder in dem stire oder in der wage oder in dem krebße",
            "routes_across_sections": True,
            "routing_detail": "Cross-links f155r bathing rules to bloodletting/cupping limb-sign ban (f155r), pre/post-bath digestion & heat progression (f155v-f156v), and closing lunar/zodiac election block (f170v-f171r).",
            "source_paths": [
                "../../readers/bf/bf914217488dd0eed747ceb4a8db9708a95d6bc6acd395721e0e9581eea17486.jpg",
                "5a1206d3a2c4922c3c9e1baa.md",
                "../../../resources/readers/collection/manuscripts/Heidelberg_Cpg_213/REFERENCE.source.html",
            ],
            "limits": "Direct image reading of 0319_155r.jpg; 'storpion' is scribal spelling for Scorpio; Aquarius is neither in the 7-sign favorable list nor in the 4-sign Haly avoidance list here (Aquario appears as authority name for waning moon).",
        },
        {
            "rule_id": "R-CPG213-155R-AVOID-HALY",
            "witness_shelfmark": "Heidelberg, UB, Cod. Pal. germ. 213",
            "manuscript_date_place": "1421 colophon (Fascicle II, f171r); East Franconian / Bavarian",
            "folio_locus": "f155r (Regel der Gesundheit, ch. 22)",
            "rule_type": "MOON_IN_SIGN_BATH",
            "input_condition": "Moon in 'hot signs' (heyßen zeichen): Leo, Virgo, Gemini, or Capricorn (attr. Haly)",
            "gate": "AVOID",
            "bath_parameter": "Bathhouse / sweat-bath (yn die badstuben gen)",
            "signs_covered": ["Leo", "Virgo", "Gemini", "Capricorn"],
            "verbatim_excerpt": "Haly der meyster spricht man sal in keyme heyßen zeichen yn die badstuben gen als in dem lewen vnd in der Juckfrauwe vnd in dem czwiling vnd in dem steinbocke",
            "routes_across_sections": True,
            "routing_detail": "Pairs with f155r favorable 7-sign list and f170v-f171r closing lunar election (which swaps Gemini for Aquarius).",
            "source_paths": [
                "../../readers/bf/bf914217488dd0eed747ceb4a8db9708a95d6bc6acd395721e0e9581eea17486.jpg",
                "../../../resources/readers/collection/manuscripts/Heidelberg_Cpg_213/REFERENCE.source.html",
            ],
            "limits": "Direct image reading of 0319_155r.jpg. Preserve local grouping of Virgo/Gemini/Capricorn under 'hot signs' without normalizing to standard elemental triplicities.",
        },
        {
            "rule_id": "R-CPG213-170V-FAV-AVOID",
            "witness_shelfmark": "Heidelberg, UB, Cod. Pal. germ. 213",
            "manuscript_date_place": "1421 colophon (Fascicle II, f171r); East Franconian / Bavarian",
            "folio_locus": "f170v (closing lunar/zodiac election unit, rubric 'In welchem zeichen man las[sen] sol', attr. Abenragel & Haly)",
            "rule_type": "MOON_IN_SIGN_BATH",
            "input_condition": "FAVORABLE: Moon waning + Aries, Scorpio, Pisces, Sagittarius, Taurus, Libra, or Cancer. AVOID (bathhouse): Leo, Virgo, Capricorn, or Aquarius",
            "gate": "QUALIFIED",
            "bath_parameter": "Bathing & cupping (Moon waning); bathhouse / sweat-bath (badstuben) barred in 4 named signs",
            "signs_covered": ["Aries", "Scorpio", "Pisces", "Sagittarius", "Taurus", "Libra", "Cancer", "Leo", "Virgo", "Capricorn", "Aquarius"],
            "verbatim_excerpt": "Wenne du aber baden oder schrepffen wild so sol er syn yn dem abnemen ... Wer do baden wil der sol baden in Ariete oder scorpione oder in pysibus oder in sagittario oder in thauro oder in libra oder in Cancro spricht haly // Man sol in keim zeichen yn die badstuben gen als in leone in virgine in Capricorno vnd aquario",
            "routes_across_sections": True,
            "routing_detail": "Re-collects zodiacal elections for phlebotomy (Aries/Libra/Sagittarius/Aquarius), bathing/cupping, surgery (f171r), and new clothes (f171r Leo ban) at the end of the Regel.",
            "source_paths": [
                "../../readers/27/273d6ada0c5de2dbf40d61172a44531909ed1caeeef1fca126f5b0a17974dcc9.jpg",
                "../../readers/14/144f0b7a0308199a4770088ff8469e57284a99d501b3227b4357e374228c67e4.jpg",
                "../../../resources/readers/collection/manuscripts/Heidelberg_Cpg_213/REFERENCE.source.html",
            ],
            "limits": "Direct image reading of 0350_170v.jpg. Note witness-internal variant: f170v places Aquarius in Haly's badstuben avoidance list where f155r placed Gemini.",
        },
        {
            "rule_id": "R-CPG557-77V-FAV-AVOID",
            "witness_shelfmark": "Heidelberg, UB, Cod. Pal. germ. 557",
            "manuscript_date_place": "1468 (colophon f96v); Northern Lake Constance / High Alemannic-Swabian",
            "folio_locus": "f77v (Regel ch. 22, following f77r rubric 'Ein capitel vo dem baden wen schwaiss baden gut sey vnd auch wasser baden')",
            "rule_type": "MOON_IN_SIGN_BATH",
            "input_condition": "FAVORABLE: Moon waning (attr. Aquario) + Aries, Scorpio, Pisces, Sagittarius, Taurus, Libra, or Cancer. AVOID: hot signs (haissen zaichen), specifically Leo and Capricorn",
            "gate": "QUALIFIED",
            "bath_parameter": "Sweat bath in bathhouse (badstuben) vs water bath (wasser bad); plus f77v-78r warm foot/leg washing & head washing every 15/20 days",
            "signs_covered": ["Aries", "Scorpio", "Pisces", "Sagittarius", "Taurus", "Libra", "Cancer", "Leo", "Capricorn"],
            "verbatim_excerpt": "Aquario der maist[er] spricht wen man baden wil oder schrepffen So sol der mo[n] sein in dem ab neme ... Wer baden wil der sol bade[n] so dy mon ist in dem wider oder in dem scorpion oder Im fisch oder in dem schucze[n] oder Im stier oder in der wag oder Im kreps haly der maist[er] schreibt man solle in keine[n] haissen zaichen in dy badstuben gan als In dem leo In dem steinbock",
            "routes_across_sections": True,
            "routing_detail": "Links f77r-78v bathing types/lunar gates to f79r-81v pre/post-bath digestion & heat progression, f84r-89r cupping/bloodletting sites, and f19v-20v Moon-in-signs lookup table (though f19v grades general goodness, not bath specifically).",
            "source_paths": [
                "../../readers/53/532d0d5e713e036cb3146ef4e0143adbdd10d18600d0b1c6132c382f7b17cd27.jpg",
                "../../../resources/readers/collection/manuscripts/Heidelberg_Cpg_557/REFERENCE.source.html",
                "d23573606894bb2be346be66.json",
            ],
            "limits": "Direct image reading of 0156_77v.jpg. Cpg 557's Haly list names only Leo and Capricorn (omitting Virgo and Gemini present in Cpg 213 f155r and Cpg 291 f44r); 'ab neme' (waning) supersedes predecessor Gemini reading.",
        },
        {
            "rule_id": "R-CPG291-43V44R-FAV-AVOID",
            "witness_shelfmark": "Heidelberg, UB, Cod. Pal. germ. 291",
            "manuscript_date_place": "1477-1496 (Bavaria; Passau/Freising calendar; Schürstab Hausbuch)",
            "folio_locus": "f43v-f44r (bath miniature at 43v; Regel ch. 22 prose 43v-44r)",
            "rule_type": "MOON_IN_SIGN_BATH",
            "input_condition": "FAVORABLE: Moon waning (attr. Aquario) + Aries, Scorpio, Pisces, Sagittarius, Taurus, Libra, or Cancer. AVOID: hot signs (haissen zaichen), specifically Leo, Virgo, Gemini, and Capricorn",
            "gate": "QUALIFIED",
            "bath_parameter": "Sweat bath in bathhouse (padstuben / stuben) vs water bath (wasserpad); warm leg/foot wash; head wash every 15-20 days; bath miniature (2 bathers in stave tub under starred sky)",
            "signs_covered": ["Aries", "Scorpio", "Pisces", "Sagittarius", "Taurus", "Libra", "Cancer", "Leo", "Virgo", "Gemini", "Capricorn"],
            "verbatim_excerpt": "Aquario der maist[er] spricht Wenn man paden oder schrepffen wil So sol der mon sein in dem abnemen ... Wer paden wil der sol paden in dem wyd[er] So der mon darinn ist Oder in dem Scorpion Oder in den Vischen Auch in dem Schützen In dem Stier In der Wag Oder in dem krebs Haly d[er] maist[er] spricht man sull in kainem haissen zaichen paden oder in die stuben geen Als in dem leo in d[er] Junckfraw in dem Zwiling Und in dem Stainpock",
            "routes_across_sections": True,
            "routing_detail": "Embedded within the Schürstab Hausbuch sequence linking calendar/Moon-in-sign tables, sign medallions (10r-18v), zodiac man (42v), bath chapter + miniature (43v-44r), and vein man (52r).",
            "source_paths": [
                "815938da297754f27079cb13.jpg",
                "afcbb8e1f487fddcad7a44d5.jpg",
                "../../../resources/tools/provenance/index.html#s-ab77814892685015",
            ],
            "limits": "Direct image reading of 102_43v.jpg and 103_44r.jpg. Matches Cpg 213 f155r on all 7 favorable and all 4 avoided signs.",
        },
        {
            "rule_id": "R-WELLCOME438-497-FAV-AVOID",
            "witness_shelfmark": "London, Wellcome Collection, MS.438 (b19672676)",
            "manuscript_date_place": "1429 verse date (p. 332); c. 1475 copy (Upper German / Swiss; Laufenberg + Practica)",
            "folio_locus": "p. 497 (PDF p. 459, lower Practica items)",
            "rule_type": "MOON_IN_SIGN_BATH",
            "input_condition": "FAVORABLE: Moon in Aries, Scorpio, Pisces, Sagittarius, Cancer, Libra, or Taurus (BEST in Cancer or Pisces). AVOID: hot signs when taking medicine for palsy and moist illnesses",
            "gate": "QUALIFIED",
            "bath_parameter": "Bathing in general; conditional ban during internal medicinal treatment for palsy ('parle') and moist/phlegmatic diseases ('fuochten siechtagen')",
            "signs_covered": ["Aries", "Scorpio", "Pisces", "Sagittarius", "Cancer", "Libra", "Taurus"],
            "verbatim_excerpt": "Item es ist gut ze baden so der mon ist jn dem wider oder jn Scorpione / Im fisch / Im schutzen / Im krebs / jn der wäg oder Im stier Es ist aber allerbest Im krebs oder im fischen ¶ Item man sol nit baden in den hitzigen zeichen wen[n] so man sich artznen wil zuo dem parle vnd zuo fuochten siechtagen",
            "routes_across_sections": True,
            "routing_detail": "Appears at close of Practica (p. 497), independent of p. 55 general sign-grading table (which marks Scorpio/Taurus 'bös' and Cancer/Pisces 'mittel') and pp. 336-345 conflicting monthly regimens.",
            "source_paths": [
                "be54fb9f75a383cbe63d233d.pdf",
                "../../../resources/tools/provenance/index.html#s-fd240bbc8cb4541f",
                "b1ef323fd56bd1846ced33eb.md",
            ],
            "limits": "Verified directly on PDF page 459 (MS p. 497). Copy dated c. 1475; hot signs are barred conditionally (when taking medicine for palsy/moist disease), not listed by name on p. 497.",
        },
        {
            "rule_id": "R-IF35-22V-GRID",
            "witness_shelfmark": "Prague, Národní knihovna České republiky, I F 35 (Confundarium)",
            "manuscript_date_place": "1431 (completed by Matouš Beran at Erfurt, 12 May 1431)",
            "folio_locus": "f22v, row 26 ('Balneari')",
            "rule_type": "MOON_IN_SIGN_BATH_GRID",
            "input_condition": "Moon's sign by mean motion across 12 sign columns (Aries..Pisces)",
            "gate": "QUALIFIED",
            "bath_parameter": "Bathing ('Balneari'): B (good) = Cancer, Leo, Sagittarius, Pisces; m (middle) = Aries, Taurus, Gemini, Virgo, Libra, Scorpio, Aquarius; o (bad) = Capricorn",
            "signs_covered": SIGNS_12,
            "verbatim_excerpt": "Row label 'Balneari': m m m B B m m m B o m B (Aries through Pisces)",
            "routes_across_sections": True,
            "routing_detail": "f23r explicitly refers reader from the 42-row grid (ff22v-23r) to the fuller Moon-in-sign prose at ff24r-28r; grid and prose disagree at Aries (m vs B), Capricorn (o vs qualified B), and Aquarius (m vs B).",
            "source_paths": [
                "cb7449e9c540c4bbb08c6e25.json",
                "../../../resources/tools/provenance/index.html#s-8427725bda1c7721",
            ],
            "limits": "Retained B/m/o normalization from 745_praguenk_if35_beran_gap2.md; no universal precedence rule between grid and prose in manuscript.",
        },
        {
            "rule_id": "R-IF35-24R-28R-PROSE",
            "witness_shelfmark": "Prague, Národní knihovna České republiky, I F 35 (Confundarium)",
            "manuscript_date_place": "1431 (completed by Matouš Beran at Erfurt, 12 May 1431)",
            "folio_locus": "ff24r-28r (twelve Moon-in-sign prose sections + verses)",
            "rule_type": "MOON_IN_SIGN_BATH",
            "input_condition": "Moon in Aries (favorable bath, avoid head-washing), Cancer (favorable), Leo (verse unresolved), Sagittarius (favorable), Capricorn (favorable with unread condition), Aquarius (favorable); Taurus/Gemini/Virgo/Libra/Scorpio/Pisces silent on sign-bath (Scorpio general 'nothing good')",
            "gate": "QUALIFIED",
            "bath_parameter": "Entering the bath ('balneum intrare' / 'balneari'); Aries explicitly bars head washing ('Malum est caput lavare')",
            "signs_covered": ["Aries", "Cancer", "Leo", "Sagittarius", "Capricorn", "Aquarius", "Scorpio"],
            "verbatim_excerpt": "Aries 24r L15: 'balneum intrare' (Bonum est); L17-18: 'Malum est caput lavare'; 24v L10: 'balnea tucius intres'. Cancer 25r L32: Bonum 'Balneari'. Leo 26r L4: 'Balnea cum socio (?) tunc nullum (?) constat (?) habere' (sense unread). Sagittarius 26v L34: 'Bonum est balneum intrare'. Capricorn 27r L19-20: 'Bonum est balneari si non mi...'. Aquarius 27v L4: bonum 'balneari'. Scorpio 26v L12-15: 'Non video quid in eo sit bonum incipere vel facere, quia luna tunc est in casu'.",
            "routes_across_sections": True,
            "routing_detail": "Directly linked by f23r referral from f22v grid; also embeds date-based perilous-days water/bath warnings inside Virgo (August 26r L21-25), Libra (September 26v L3-7), and Aquarius (January 27v L14-18) sections.",
            "source_paths": [
                "../../../resources/tools/provenance/index.html#s-8427725bda1c7721",
                "66b3a3bbc4dc27558806daeb.txt",
            ],
            "limits": "Embedded August/September/January water/bath bans are calendar month perilous-days rules, NOT Moon-in-sign rules; Leo verse and Capricorn 'si non mi...' condition remain partly unresolved.",
        },
        {
            "rule_id": "R-CAIUS336-128V129R-ARIES",
            "witness_shelfmark": "Cambridge, Gonville and Caius College, MS 336/725",
            "manuscript_date_place": "Late 15th century, England (Part 2 moonbook)",
            "folio_locus": "ff128v-129r (Aries entry in 12-sign moonbook ff128v-130v)",
            "rule_type": "MOON_IN_SIGN_BATH",
            "input_condition": "Moon in Aries (favorable to be bathed and stewed; avoid head medicine/cutting/vein-opening)",
            "gate": "FAVORABLE",
            "bath_parameter": "Bathing and stewing ('to be bathed and stewed'); excludes head medicine/cutting/vein opening",
            "signs_covered": ["Aries"],
            "verbatim_excerpt": "Aries ... whan the mone is in this signe be war of kuttynge in the hed or in the face or of openynge of any veyne that longeth to the hed ... and this masculyne is good to worche al thynge that is faire as to be bathed and stewed and suche other",
            "routes_across_sections": False,
            "routing_detail": "Self-contained 12-sign moonbook entry (ff128v-130v). Remaining 11 signs (Taurus-Pisces on ff129r-130v) give limb-cutting/bloodletting/ventusing/sowing/prognosis rules without bathing clauses.",
            "source_paths": [
                "../../readers/2b/2b4825c329cca9ec83d6f58b57ca02c4bc0e4abe3eb25c8447626df0c2ff6c1e.jpg",
                "../../readers/4f/4f8a7d88bc9c00d16e01a7895827eff87e98d2ac365caea1f409b1a8eddaa834.jpg",
                "../../../resources/tools/provenance/index.html#s-3fa5dee07e563403",
            ],
            "limits": "Direct image reading of caius336_128v.jpg–130v.jpg confirms bathing/stewing is explicitly named only under Aries in ff128v-130v.",
        },
        {
            "rule_id": "R-POL3227A-68V-ARIES",
            "witness_shelfmark": "Nuremberg, GNM, Hs. 3227a (Pol Hausbuch)",
            "manuscript_date_place": "c. 1389-1420 (Nuremberg)",
            "folio_locus": "f68v (Moon-in-sign hexameters with red connector lines to body-part labels)",
            "rule_type": "MOON_IN_SIGN_BATH",
            "input_condition": "Moon in Aries (do not treat head; bleed and enter the bath more safely)",
            "gate": "FAVORABLE",
            "bath_parameter": "Entering the bath ('balnea tucius intres'); head treatment prohibited",
            "signs_covered": ["Aries"],
            "verbatim_excerpt": "68v Moon in Aries: do not treat the head; bleed and enter the bath more safely ('minuas et balnea tucius intres')",
            "routes_across_sections": True,
            "routing_detail": "68v red connector lines join body-part labels to sign labels; shares melothesia mapping with f159r zodiac man list, though f159r adds no separate bath rule.",
            "source_paths": [
                "788e12f54db056be1a71e170.md",
            ],
            "limits": "Taurus through Pisces on f68v carry phlebotomy, potion, surgery, and nail/hair rules, with no further bathing entries.",
        },

        # --- 2. LUNAR MANSION NATIVITY WATER-RISK WITNESS (NOT BATH ELECTION; Q-M15 PRESERVED) ---
        {
            "rule_id": "R-CGM7958-MANSIONS-Q-M15",
            "witness_shelfmark": "Munich, BSB, Cgm 7958 (Hartlieb Mondwahrsagebuch / 28 Lunar Mansions)",
            "manuscript_date_place": "Mid-15th century (1456 substrate context), Bavaria",
            "folio_locus": "fol. 3r-9v (specifically M8 fol. 5r, M9 fol. 5r, M13 fol. 6r-6v, M15 fol. 6v-7r, M20 fol. 7v-8r, M24 fol. 8v)",
            "rule_type": "LUNAR_MANSION_NATIVITY_WATER_RISK",
            "input_condition": "Person BORN under lunar mansion ('wer dar under geporn wirt') — nativity life-risk, NOT Moon-in-mansion bathing election",
            "gate": "AVOID",
            "bath_parameter": "Water / drowning hazard warning ('sal sich hüten vor wassen' in M15; 'vor wasser' in M13/M20/M24; 'wasin/wassen' in M8/M9) — NOT a bath temperature or bath-type prescription",
            "signs_covered": ["Cancer (M8-M9)", "Virgo (M13, M15 border)", "Sagittarius (M20)", "Aquarius (M24)"],
            "verbatim_excerpt": f"M15 (fol. 6v-7r, Algofara/Al-Ghafr): '{cgm7958_data['m15_q_m15_record']['source_text_verbatim']}'",
            "routes_across_sections": False,
            "routing_detail": "Birth-mansion prose series only; modern TSV cross-reference columns ('Zone 2', 'f79r') are unverified hypotheses and explicitly excluded from historical rules.",
            "source_paths": [
                "efab4fcc99e45a1be5f1b1d4.tsv",
            ],
            "limits": cgm7958_data["m15_q_m15_record"]["q_m15_qualifier"],
        },

        # --- 3. CATALOG-ATTESTED UNINSPECTED ZODIAC-TO-BATH WITNESS ---
        {
            "rule_id": "R-WELLCOME549-86V-CATALOG",
            "witness_shelfmark": "London, Wellcome Collection, MS.549 (Miscellanea Medica XXIII)",
            "manuscript_date_place": "1471",
            "folio_locus": "f86v (following item 1: Sigismund Albicus, Regimen hominis ff2-86)",
            "rule_type": "CATALOG_ATTESTED_UNINSPECTED",
            "input_condition": "Zodiacal signs and corresponding aspects (uninspected table; blocked-acquisition in substrate)",
            "gate": "CATALOG_UNINSPECTED",
            "bath_parameter": "Bloodletting, baths, etc. (exact sign grades unavailable on disk)",
            "signs_covered": [],
            "verbatim_excerpt": f"{w549_cat['header_excerpt']} ... {w549_cat['f86v_excerpt']}",
            "routes_across_sections": False,
            "routing_detail": "Follows Albicus Regimen hominis (ff2-86); manuscript is blocked-acquisition (IIIF b19507392 has no child manifests), so f86v cell values cannot be verified or populated.",
            "source_paths": [
                "../../../resources/readers/collection/voynich/wellcome_mss_pre1650_catalogue_djvu.txt",
            ],
            "limits": "Catalog-attested only; no primary folio image on disk; sign cells must NOT be guessed or extrapolated from Albicus MS 16 or Pal. lat. 1257.",
        },

        # --- 4. MONTH / SEASON / PHASE / POST-OP BATH GATES (NON-ZODIAC-SIGN) ---
        {
            "rule_id": "R-CPG5-17R17V-MONTH",
            "witness_shelfmark": "Heidelberg, UB, Cod. Pal. germ. 5",
            "manuscript_date_place": "First quarter 15th century, Bavaria",
            "folio_locus": "f16r (pre-bleeding warm bath); ff17r-17v (Monatsregimen Jan-Dec)",
            "rule_type": "MONTH_GATED_BATH",
            "input_condition": "Month / blood thickness (Feb-Apr sweat bath; May herb water bath; Nov avoid much bathing; pre-bleeding arm bath for thick blood)",
            "gate": "QUALIFIED",
            "bath_parameter": "Sweat bath (sweissbaden: Feb, Mar with agrimony, Apr); water bath (wasserbaden: May with wormwood/agrimony/hyssop); Nov limit ('nit vil baden'); pre-bleeding warm arm bath (f16r)",
            "signs_covered": [],
            "verbatim_excerpt": "f17r: Feb 'sweissbaden so die gelider switzen'; Mar sweat bath with agrimony; Apr 'vil sweissbaden'; May 'wasserbaden und sunderlich mit wermut ... agrimonien und ysopen (?)'; f17v Nov: 'Du solt nit vil baden wanne daz plut ist dir denne ze dick'; f16r: bathe or warm the arm 'also daz es hitzig werde so zerteilt sich daz plut'",
            "routes_across_sections": False,
            "routing_detail": "Pairs f16r pre-bleeding bath with ff17r-17v monthly regimen; zero zodiac-sign rules for bathing (12 signs appear only in Latin melothesia verse under f13v vein man).",
            "source_paths": [
                "899b5143d87ee8f269763c89.md",
                "../../../resources/tools/provenance/index.html#s-6dcd27ebbbde3ed5",
            ],
            "limits": "Month-gated only; not indexed by Moon-in-sign.",
        },
        {
            "rule_id": "R-CPG214-57V58V-MONTH",
            "witness_shelfmark": "Heidelberg, UB, Cod. Pal. germ. 214 (Speyrer Arzneibuch)",
            "manuscript_date_place": "1321 (Speyer)",
            "folio_locus": "ff57v-58v (Twelve-month regimen)",
            "rule_type": "MONTH_GATED_BATH",
            "input_condition": "Calendar month (Feb, Mar FAVORABLE for sweat bath; Nov AVOID sweat bath)",
            "gate": "QUALIFIED",
            "bath_parameter": "Sweat bath ('swizbade'): allowed Feb (with purge) and Mar; forbidden Nov",
            "signs_covered": [],
            "verbatim_excerpt": "57v-58v: Feb purge taken in a 'swizbade'; Mar sweat-bath allowed; Nov no sweat-bath, no intercourse (plus 59r later hand: bladder-stone powder 'so du in aim bat gast so brichet der stain')",
            "routes_across_sections": False,
            "routing_detail": "Month-keyed regimen; contains no zodiac signs or moon ages.",
            "source_paths": [
                "../../../resources/tools/provenance/index.html#s-82aef9d8ea775477",
            ],
            "limits": "Month-gated only; pre-1400 comparative witness.",
        },
        {
            "rule_id": "R-W49-45R-MONTH-PHASE",
            "witness_shelfmark": "London, Wellcome Collection, MS.49 ('Wellcome Apocalypse')",
            "manuscript_date_place": "c. 1420-1430, Thuringia / Southeast Germany",
            "folio_locus": "f45r (monthly regimen verses + moon-phase wheel; cf. f43v zodiac man/table)",
            "rule_type": "MONTH_GATED_BATH",
            "input_condition": "Calendar month (f45r monthly verse regimen with Balnea cues, e.g., Mar/Jul/Nov avoidance vs Jun 'balnea tuta'); f45r moon wheel governs washing clothes in waxing light, not body bathing",
            "gate": "QUALIFIED",
            "bath_parameter": "General bathing ('Balnea' cues in monthly regimen verses)",
            "signs_covered": [],
            "verbatim_excerpt": "f45r col. 2-3: 'Balnea sit tuta...' (Feb?); 'Balnea vitet[ur?]...' (Mar); 'et balnea tuta patebunt' (Jun); 'devitet balnea vita' (Jul); 'Balnea tu[m] vite[t] nisi nimia cogat habe[re]' (Nov)",
            "routes_across_sections": False,
            "routing_detail": "f43v carries Bona/Mala/Mediocria sign grades (for general/bloodletting/emetics), while f45r carries monthly Balnea/Vena verses and 1-29 moon wheel without linking Balnea to zodiac signs.",
            "source_paths": [
                "928dc2d3a1c99b96f7f1ac9a.jpg",
                "383f751de0a6a720ffc560ad.jpg",
                "../../../resources/tools/provenance/index.html#s-3b82683b9601ea2b",
                "66b3a3bbc4dc27558806daeb.txt",
            ],
            "limits": "f45r bathing rule is month-gated, not sign-gated; f43v sign table does not specify bathing.",
        },
        {
            "rule_id": "R-BELLIFORTIS-CPG787-CLM30150",
            "witness_shelfmark": "Heidelberg, UB, Cod. Pal. germ. 787 & Munich, BSB, Clm 30150 (Kyeser, Bellifortis)",
            "manuscript_date_place": "c. 1430 (Cpg 787 begun 1430; Clm 30150 c. 1430)",
            "folio_locus": "Cpg 787 f78v; Clm 30150 f36r (Galen herbal sweat bath)",
            "rule_type": "MONTH_GATED_BATH",
            "input_condition": "Valid in every month EXCEPT the dog-days month ('excepto mense canino', i.e., Canis/Sirius summer period)",
            "gate": "QUALIFIED",
            "bath_parameter": "Herbal sweat bath against paralysis (pila/pipe steam, tub over furnace, artemisia/valeriana/agrimonia/millefolium, as hot as bearable for 9 days)",
            "signs_covered": [],
            "verbatim_excerpt": "Clm 30150 f36r: 'Et sic lavet quanto calidus possit / Per novem ... diebus hoc continuare licebit / Valet omni mense excepto mense canino'; Cpg 787 f78v: 'valet cu[?] mense excepto mense canino'",
            "routes_across_sections": False,
            "routing_detail": "Self-contained bath recipe (paired with Philo bath Clm 30150 f35v/36v and Cpg 787 f76r, plus Clm 30150 f31r root boiled as drink with baths).",
            "source_paths": [
                "../../../resources/tools/provenance/index.html#s-603a3ff49a261844",
                "../../../resources/tools/provenance/index.html#s-49b547b232d723d8",
            ],
            "limits": "Dog-days exclusion ('mense canino') is a seasonal/star-rising calendar month gate, not a Moon-in-zodiac-sign election.",
        },
        {
            "rule_id": "R-LAUFENBERG-BERLIN1191",
            "witness_shelfmark": "Berlin, SBB, Ms. germ. fol. 1191 (Heinrich Laufenberg, Versehung des Leibs)",
            "manuscript_date_place": "1429 (verse colophon f144v), Upper Rhine / Strasbourg?",
            "folio_locus": "f5r-5v (March), f16v (November), f82v (bath chapter), f144v (hour sphere)",
            "rule_type": "MONTH_GATED_BATH",
            "input_condition": "Month (March sweat-bath good; November no sweat-bath) and 24-hour sphere (f144v rubric mentions letting and bathing by hour I-XXIIII)",
            "gate": "QUALIFIED",
            "bath_parameter": "Sweat bath (f5r 'sweisbaden güt', f5v 'Baden solt du manigvalt', f16v 'Kein sweis bad solt du han'); stave tub bath (f82v 'von baden lossen')",
            "signs_covered": [],
            "verbatim_excerpt": "f5r: 'Doch ist sweißbaden güt'; f5v: 'Baden solt du manigvalt'; f16v: 'Kein sweis bad solt du han / Din blüt swachet sich da von'; f82v rubric: 'Das vierde stuck ... von baden lossen'; f144v sphere rubric tied to letting and bathing (gut/mittel/bos by hours I-XXIIII)",
            "routes_across_sections": True,
            "routing_detail": "Cross-links month regimen, bath chapter (f82v), and closing 24-hour sphere (f144v); however, sign pages f25r-30v and missing f31r-62v do not supply a Moon-in-sign bath rule on inspected leaves.",
            "source_paths": [
                "6f4963085a16fc2c38742bcc.md",
                "../../../resources/tools/provenance/index.html#s-07ca99271041e14c",
            ],
            "limits": "Month- and hour-gated on inspected Berlin leaves (note: the Wellcome MS.438 p.497 Moon-in-sign bath rule sits in the appended prose Practica, not in Laufenberg's verse).",
        },
        {
            "rule_id": "R-WELLCOME16-ALBICUS",
            "witness_shelfmark": "London, Wellcome Collection, MS.16 (Sigismund Albicus, Regimen)",
            "manuscript_date_place": "Compiled 1422 at Wroclaw; copied 1437 by Hinricus de Geismaria",
            "folio_locus": "f4r-4v, f6v-7r, f14r, f25v-26r",
            "rule_type": "SEASON_GATED_BATH",
            "input_condition": "Season, plague state, and patient tolerance (outdoors in summer / indoors in winter; forbidden in plague; forbidden before bleeding)",
            "gate": "QUALIFIED",
            "bath_parameter": "Stepwise sweat/bath with head lye, hot footbath to knees, cool rinse, 1/2-hour rest (f4r-4v); hot 'vannia' sit to navel 1/2-1 hour (f25v)",
            "signs_covered": [],
            "verbatim_excerpt": "f25v: 'sedeatis in vannia usque ad umbilicum vel modicum superius ... sedendo per mediam vel unam horam in vannia quanto diucius potestis tolerare'; f6v: 'Abstineatis etiam a balneis' (plague)",
            "routes_across_sections": False,
            "routing_detail": "f12v-13r ties 4 moon quarters to ages/complexions for phlebotomy only; f14r names 'tempus eleccionis' without rules; zero zodiac signs appear anywhere in 42 opened pages.",
            "source_paths": [
                "a8cebc8021248e734bfc3cf5.md",
                "03aa4cbf0c6926e63f559811.md",
            ],
            "limits": "Zero zodiac-sign rules on all 42 opened pages.",
        },
        {
            "rule_id": "R-PALLAT1257-POSTOP-SEASON",
            "witness_shelfmark": "Vatican City, BAV, Pal. lat. 1257 (composite incl. Albicus Medicinalia)",
            "manuscript_date_place": "Composite, 1422-1600 (undated phlebotomy leaves)",
            "folio_locus": "f23r, f99r, f115r, f156r (contrast f22v bloodletting sign table)",
            "rule_type": "POST_TREATMENT_DAY_OR_STATE_BATH",
            "input_condition": "Day 6 after bloodletting (FAVORABLE release); immediately after bloodletting avoid hot sweet-water baths; avoid baths in rheum/headache/fever/full belly; paralytic footbath hot in winter / tepid in summer",
            "gate": "QUALIFIED",
            "bath_parameter": "General bath released on day 6 ('Balnea sexta petat', f23r); hot sweet-water bath withheld post-bleeding ('balnea in aqua dulci et calida', f156r); foot bath morning/evening by season (f99r)",
            "signs_covered": [],
            "verbatim_excerpt": "f23r: 'Balnea sexta petat'; f156r: avoid 'balnea in aqua dulci et calida'; f115r: avoid baths with 'Reuma, dolor capitis, oculi, febris, ulcera, plaga'; f99r: 'pedes debiles ut sunt paralitici debent lavari mane et sero cum vino calido in hieme, sed in estate cum tepido'",
            "routes_across_sections": False,
            "routing_detail": "f22v sign classification (Aries/Libra/Sag/Aq good; Can/Sco/Pis middle; Tau/Gem/Leo/Vir/Cap bad) explicitly governs bloodletting ('minutio'/'flebotomia'), NOT bathing.",
            "source_paths": [
                "../../../resources/tools/provenance/index.html#s-b4ac19bbfa4cbc88",
                "../../../resources/tools/provenance/index.html#s-f918935c19b29a66",
            ],
            "limits": "Bath timing is post-phlebotomy day count / physiological state / season, not zodiac sign.",
        },
        {
            "rule_id": "R-CASANATENSE4182-SEASON",
            "witness_shelfmark": "Rome, Biblioteca Casanatense, MS 4182 (Theatrum Sanitatis)",
            "manuscript_date_place": "c. 1390-1400, Lombardy",
            "folio_locus": "f.102 (Autupnus), f.103 (Hyemps)",
            "rule_type": "SEASON_GATED_BATH",
            "input_condition": "Season (Autumn dryness; Winter phlegm)",
            "gate": "FAVORABLE",
            "bath_parameter": "Bathing ('balneo') as Remotio nocumenti (counter-measure to seasonal harm)",
            "signs_covered": [],
            "verbatim_excerpt": "f.102 (Autupnus): 'Remotio nocumenti: cum rebus humectantibus et balneo'; f.103 (Hyemps): 'Nocumentum: generat flegma. Remotio nocumenti: cum calefactione igne, vestimento seu balneo'",
            "routes_across_sections": False,
            "routing_detail": "One-page-per-subject Tacuinum structure; zero zodiac signs, months, or moon ages.",
            "source_paths": [
                "../../../resources/tools/provenance/index.html#s-e8083bdfced21ff0",
                "../../../resources/tools/provenance/index.html#s-e8685022bbaabf21",
            ],
            "limits": "Seasonal counter-measure only; no zodiac or lunar gating.",
        },

        # --- 5. CHECKED NEGATIVE / NON-ZODIAC-BATH COMPARATORS ---
        {
            "rule_id": "R-NEG-MD2-13R-AND-ZODIAC",
            "witness_shelfmark": "Tübingen, UB, Cod. Md 2 (Tübinger Hausbuch)",
            "manuscript_date_place": "1470-1480, Württemberg / Swabia",
            "folio_locus": "f13r (12x7 lookup grid), ff51r-144v (12 zodiac chapters)",
            "rule_type": "NEGATIVE_CHECKED_WITNESS",
            "input_condition": "12 zodiac signs checked on f13r and ff51r-144v",
            "gate": "NONE",
            "bath_parameter": "None — f13r columns cover bloodletting (dz glieth lassen), syrup, powder, nature; zero bathing rules found in 01_calendar_block.md or 02_zodiac_prose.md",
            "signs_covered": [],
            "verbatim_excerpt": "f13r rubric headers: 'Signum / dz glieth lassen / Sirop / pulver / die natur / zeichen'",
            "routes_across_sections": False,
            "routing_detail": "Carries structural homology (12x7 grid, 319r Aquarius fountain, 42v Tierkreisfrau) without a sign-to-bath execution rule on inspected sections.",
            "source_paths": [
                "../../../resources/readers/collection/md2_dissection_2026-05-03/MD2_DISSECTION_v1.source.html",
                "e0dc69eb1938a9de9eb9c365.md",
                "883294febb4a18820e3a8935.md",
            ],
            "limits": "Md 2 ff14v-22r Regel section not fully transcribed in MD2_DISSECTION_v1.md; checked calendar/zodiac dissections contain 0 sign-to-bath rules.",
        },
        {
            "rule_id": "R-NEG-CGM288-CLM8244-M165-DD629-O720",
            "witness_shelfmark": "BSB Cgm 288; BSB Clm 8244; Morgan M.165; Cambridge UL Dd.6.29; Trinity O.7.20",
            "manuscript_date_place": "15th c. (various)",
            "folio_locus": "Cgm 288 Secretum ('Von dem pade'); Clm 8244 ff98r-145r (Tömlinger Bäderbuch); Morgan M.165; Dd.6.29; Trinity O.7.20",
            "rule_type": "NEGATIVE_CHECKED_WITNESS",
            "input_condition": "Checked on disk for explicit zodiac-to-bath execution rules",
            "gate": "NONE",
            "bath_parameter": "None recovered on disk (Cgm 288 has Secretum chapter list overlap only; Clm 8244 is chapter prose without extracted sign-gate; M.165 has 125r 1-30 table & regimen without zodiac-bath rule; Dd.6.29/O.7.20 have zodiac/bloodletting/astronomy without bath rules)",
            "signs_covered": [],
            "verbatim_excerpt": "Cgm 288 chapter title: 'Von dem pade'; Clm 8244 canvas 210: 'Das siebent capitel'",
            "routes_across_sections": False,
            "routing_detail": "Retained as negative/null-for-zodiac-bath comparators.",
            "source_paths": [
                "../../../resources/tools/provenance/index.html#s-fdcc59f9d2fb0477",
                "ad4d2e32c863221766295445.md",
                "../../../resources/tools/provenance/index.html#s-483bcc22bff979e2",
                "../../../resources/tools/provenance/index.html#s-316e65c098693924",
                "cb7449e9c540c4bbb08c6e25.json",
            ],
            "limits": "Unopened/untranscribed leaves in Cgm 288, Clm 8244, and M.165 remain outside current transcription scope.",
        },
    ]
    return rules


def build_12_sign_matrix(if35_grid: dict, cgm7958_data: dict) -> list[dict]:
    """
    Construct the 12-sign cross-witness bathing matrix (Aries through Pisces),
    strictly tracking each witness's exact gate/classification.
    """
    cpg213_155r_fav = {"Aries", "Scorpio", "Pisces", "Sagittarius", "Taurus", "Libra", "Cancer"}
    cpg213_155r_avoid = {"Leo", "Virgo", "Gemini", "Capricorn"}
    cpg213_170v_fav = cpg213_155r_fav
    cpg213_170v_avoid = {"Leo", "Virgo", "Capricorn", "Aquarius"}
    cpg557_77v_fav = cpg213_155r_fav
    cpg557_77v_avoid = {"Leo", "Capricorn"}
    cpg291_44r_fav = cpg213_155r_fav
    cpg291_44r_avoid = {"Leo", "Virgo", "Gemini", "Capricorn"}
    w438_497_fav = cpg213_155r_fav
    w438_497_best = {"Cancer", "Pisces"}

    if35_prose_map = {
        "Aries": "FAVORABLE ('balneum intrare' 24r L15; 'balnea tucius intres' 24v L10) + AVOID head wash ('Malum est caput lavare' 24r L17-18)",
        "Taurus": "SILENT on sign-bath (neck/head medicine/cutting barred 24v)",
        "Gemini": "SILENT on sign-bath (arms barred 25r)",
        "Cancer": "FAVORABLE ('Balneari' 25r L32; Moon in own house)",
        "Leo": "UNRESOLVED verse ('Balnea cum socio (?) tunc nullum (?) constat (?) habere' 26r L4)",
        "Virgo": "SILENT on sign-bath (embedded August month rule: 'caveat homo ne intret aquas' 26r L21-25)",
        "Libra": "SILENT on sign-bath (embedded September month rule: avoid waters 26v L3-7)",
        "Scorpio": "SILENT on sign-bath (general 'Non video quid in eo sit bonum' 26v L12-15)",
        "Sagittarius": "FAVORABLE ('Bonum est balneum intrare' 26v L34; 'potes (?) tunc balnea' 27r L14)",
        "Capricorn": "QUALIFIED_FAVORABLE ('Bonum est balneari si non mi...' 27r L19-20; condition unread)",
        "Aquarius": "FAVORABLE ('balneari' 27v L4; embedded January month rule: bath warning 27v L17)",
        "Pisces": "SILENT on sign-bath (feet barred 27v)",
    }

    if35_prose_gate = {
        "Aries": "FAVORABLE (head wash AVOID)",
        "Taurus": "SILENT",
        "Gemini": "SILENT",
        "Cancer": "FAVORABLE",
        "Leo": "UNRESOLVED",
        "Virgo": "SILENT (+Aug water AVOID)",
        "Libra": "SILENT (+Sep water AVOID)",
        "Scorpio": "SILENT (general AVOID)",
        "Sagittarius": "FAVORABLE",
        "Capricorn": "QUALIFIED",
        "Aquarius": "FAVORABLE (+Jan bath AVOID)",
        "Pisces": "SILENT",
    }

    # Note: 28 lunar mansions span ~12.86 deg each; approximate traditional zodiacal span
    # only for indexing where water-warning mansions sit, keeping exact mansion numbers explicit.
    cgm7958_water_by_sign = {
        "Aries": "No water warning in M1-M2 (Alnatsia, Albothaim)",
        "Taurus": "No water warning in M3-M4 (Aldortsija, Algebirn)",
        "Gemini": "No water warning in M5-M7 (Almnisin, Alcija, Albanimin)",
        "Cancer": "Nativity water/weapon warning in M8 (Almatia fol. 5r) & M9 (Alkaeff fol. 5r: 'vor allen wasin und swertn') — NOT bath election",
        "Leo": "No water warning in M10-M12",
        "Virgo": "Nativity water/fall death warning in M13 (Alhana fol. 6r-6v: 'von wasser oder von einem vall') & M15 (Algofara fol. 6v-7r, Virgo/Libra border: 'sal sich hüten vor wassen'; Q-M15 alignment qualifier applies) — NOT bath election",
        "Libra": "M15 (Al-Ghafr, Virgo/Libra) water warning ('sal sich hüten vor wassen'; Q-M15 applies); M16 no water warning",
        "Scorpio": "No water warning in M17-M19",
        "Sagittarius": "Nativity water-fear warning in M20 (Almara fol. 7v-8r: 'grösß ängst und not im wasser'); M21 explicitly NOT water death ('stirbt er nicht von wassen')",
        "Capricorn": "No water warning in M22",
        "Aquarius": "Nativity water-death abroad warning in M24 (Aldofalets fol. 8v: 'im wasser verderbn in einem fromdn land')",
        "Pisces": "No water warning in M26-M28",
    }

    grid_map = {"B": "FAVORABLE (B)", "m": "MIDDLE (m)", "o": "AVOID (o)"}

    matrix = []
    for sign in SIGNS_12:
        c213_155 = "FAVORABLE" if sign in cpg213_155r_fav else ("AVOID (badstuben/hot)" if sign in cpg213_155r_avoid else "OMITTED")
        c213_170 = "FAVORABLE" if sign in cpg213_170v_fav else ("AVOID (badstuben)" if sign in cpg213_170v_avoid else "OMITTED")
        c557_77 = "FAVORABLE" if sign in cpg557_77v_fav else ("AVOID (badstuben/hot)" if sign in cpg557_77v_avoid else "OMITTED")
        c291_44 = "FAVORABLE" if sign in cpg291_44r_fav else ("AVOID (stuben/hot)" if sign in cpg291_44r_avoid else "OMITTED")
        if sign in w438_497_best:
            w438 = "FAVORABLE (BEST: allerbest)"
        elif sign in w438_497_fav:
            w438 = "FAVORABLE"
        else:
            w438 = "OMITTED (hot signs AVOID if taking medicine for palsy/moist disease)"

        if35_g = grid_map[if35_grid["sign_grades"][sign]]
        if35_p = if35_prose_gate[sign]
        caius = "FAVORABLE (bathed & stewed; head med AVOID)" if sign == "Aries" else "SILENT on bath"
        pol = "FAVORABLE (balnea tucius intres; head AVOID)" if sign == "Aries" else "SILENT on bath"

        # Compute explicit counts across the 9 sign-keyed bath election columns
        cols = [c213_155, c213_170, c557_77, c291_44, w438, if35_g, if35_p, caius, pol]
        fav_n = sum(1 for x in cols if x.startswith("FAVORABLE") or x.startswith("QUALIFIED"))
        avoid_n = sum(1 for x in cols if "AVOID" in x and not x.startswith("SILENT") and not x.startswith("OMITTED") and not x.startswith("FAVORABLE"))
        mid_n = sum(1 for x in cols if x.startswith("MIDDLE"))
        silent_n = sum(1 for x in cols if x.startswith("SILENT") or x.startswith("OMITTED") or x.startswith("UNRESOLVED"))

        matrix.append({
            "sign": sign,
            "cpg213_f155r": c213_155,
            "cpg213_f170v": c213_170,
            "cpg557_f77v": c557_77,
            "cpg291_f44r": c291_44,
            "wellcome438_p497": w438,
            "if35_f22v_grid": if35_g,
            "if35_ff24r_28r_prose": if35_prose_map[sign],
            "caius336_ff128v_130v": caius,
            "pol3227a_f68v": pol,
            "cgm7958_nativity_water_risk_non_election": cgm7958_water_by_sign[sign],
            "wellcome549_f86v": "CATALOG_UNINSPECTED (blocked-acquisition)",
            "tally_9_election_columns": {
                "favorable_or_qualified": fav_n,
                "explicit_avoid": avoid_n,
                "middle": mid_n,
                "silent_omitted_or_unresolved": silent_n,
            },
        })
    return matrix


def build_join3_crosscheck(matrix_12: list[dict], join3: dict) -> dict:
    by_sign = {r["sign"]: r for r in matrix_12}
    return {
        "scientific_separation_rule": (
            "Historical comparator procedures and MS 408 structural findings are kept strictly separate. "
            "No historical rule is used to decode Voynichese words or assert botanical/medical identities."
        ),
        "overall_verdict": "UNDERDETERMINES_WITH_PARTIAL_CONTRADICTION_ON_VIRGO",
        "anchors_checked": [
            {
                "ms408_anchor": "Light Taurus (f71v) <-> Quire 13 f83v.P3 (and store f88v.P2)",
                "ms408_observed_facts": {
                    "whole_group_intersection": "okol (2/12 zodiac panels: f71v.12 G29/30, f73v.1) x okaiin (7 hits on 5 panels: f71v.18 G7/11, etc.) selects f71v alone at whole-group scope.",
                    "f71v_visual_selector": "f71v.14 arcaded tub is 1/15 unique whole-panel; green hat is 5/15.",
                    "f83v_P3_overlap": f"f83v.P3 contains unique Quire-13 shldy (1/917 loci at f83v.24 G6), okol (f83v.25), cheedy (f83v.24), and shares {join3['f71v_light_taurus']['f83v_P3_overlap']['shared_distinct_complete_groups']} distinct complete groups with f71v.12 (out of 27 vs 58 groups).",
                },
                "historical_taurus_profile": by_sign["Taurus"],
                "cross_check_verdict": "UNDERDETERMINES",
                "explanation": (
                    "The German Regel/Practica branch (Cpg 213 f155r/170v, Cpg 557 f77v, Cpg 291 f44r, Wellcome MS 438 p.497) "
                    "lists Taurus among 7 FAVORABLE bathing signs (5/9 columns), whereas I F 35 grid marks Taurus 'm' (middle) "
                    "and I F 35 prose, Caius 336/725 f129r, and Pol f68v are SILENT on bathing in Taurus. Crucially, ZERO "
                    "historical comparators single out Taurus as the privileged or unique bathing sign (Wellcome MS 438 p.497 "
                    "explicitly singles out Cancer and Pisces as 'allerbest', and I F 35 prose picks Aries, Cancer, Sagittarius, "
                    "Capricorn[?], Aquarius), nor do any comparators link Taurus to arcaded tubs or a specific bath sub-unit."
                ),
            },
            {
                "ms408_anchor": "Virgo (f72v2) chip-contiguous intersection & star-absent selector (.24)",
                "ms408_observed_facts": {
                    "chip_contiguous_intersection": "o·k·o·l inside f72v2.1 G36 (okolsaiin) + o·k·a·[M2]·n core in f72v2.21 (okaiin[:y]) retains f72v2 alongside f71v.",
                    "f72v2_visual_selector": "f72v2.24 (opalg) is unique star-absent figure (1/30 across Virgo) beside .23 (oeedy, sole untinted outline star 1/30).",
                },
                "historical_virgo_profile": by_sign["Virgo"],
                "cross_check_verdict": "CONTRADICTS_FAVORABLE_BATH_READING_OR_UNDERDETERMINES",
                "explanation": (
                    "Across all 9 sign-keyed historical bath columns, Virgo receives 0 FAVORABLE votes: Cpg 213 (f155r and f170v) "
                    "and Cpg 291 (f44r) explicitly classify Virgo as AVOID for bathhouse entry ('badstuben', under Haly's hot-sign rule); "
                    "I F 35 f22v grades Virgo 'm' (middle) and its Virgo prose (f26r) embeds the August 'caveat homo ne intret aquas' "
                    "warning; Caius 336/725 f129v and Pol f68v are silent on bathing; and Cgm 7958 M13/M15 record nativity water hazards "
                    "(not elections, Q-M15). Therefore, if MS 408's f71v+f72v2 intersection were read as 'both signs favor bathing', "
                    "historical elections contradict Virgo; alternatively, if f72v2 represents a non-bath or contraindication/avoidance gate, "
                    "no MS 408 rubric confirms that polarity and historical rules do not predict star-absence (.24)."
                ),
            },
            {
                "ms408_anchor": "Pale Aries (f71r) oteeol (.15 <-> .18) & lunar .72-74 intersection",
                "ms408_observed_facts": {
                    "f71r_selector": "f71r.15 figure label 'oteeol' matches f71r.18 G1/10 inner band 'oteeol' (1/15 on f71r; 1/30 across both Aries panels).",
                    "assembly_note": "In MASTER_ASSEMBLY, Pale Aries f71r oteeol links .15 to .18 while solar oteey·dar and inner-ring okeeody converge on lunar .72-74.",
                },
                "historical_aries_profile": by_sign["Aries"],
                "cross_check_verdict": "COMPATIBLE_ON_BATH_APPROVAL_BUT_NON_PREDICTIVE",
                "explanation": (
                    "Aries has the strongest historical bathing approval (8/9 columns FAVORABLE, 1/9 MIDDLE in I F 35 f22v grid), "
                    "confirming that Aries is routinely paired with bathing in medieval iatromathematics. However, historical Aries "
                    "rules also pair bathing approval with explicit HEAD-WASHING / HEAD-TREATMENT PROHIBITIONS (I F 35 24r/24v "
                    "'Malum est caput lavare'; Caius 128v-129r; Pol 68v), and provide no structural prediction for f71r's single "
                    "label-to-inner-band repeat ('oteeol') or lunar-to-solar convergence."
                ),
            },
            {
                "ms408_anchor": "Quire 13 f75v crown-directed delivery & blue-vs-green RGB separation",
                "ms408_observed_facts": {
                    "f75v_rgb": "Blue neck circle (B-R=+16.4), upper band left (B-R=+1.1), lower pool (B-R=-1.6) vs green upper trough (B-R=-25.6, G-B=+25.1).",
                    "f75v_labels": "5 same-face P0 matches (qokal, dal, olol, otedy, qotedy); 1 okaiin (f75v.42), 2 cheedy, 1 olshedy + 1 ol.shedy (f75v.47); 0 okol, 0 shldy.",
                },
                "historical_comparators": "Celsus De medicina I.4 (cold head conduit, non-zodiacal); Morgan G.74 f12r (head pouring, non-zodiacal); I F 35 f24r (Aries forbids head washing); Cpg 213/557/291 (warm foot/leg wash, head wash every 15-20 days, not sign-gated).",
                "cross_check_verdict": "UNDERDETERMINES_AND_TENSION_ON_HEAD_RULE",
                "explanation": (
                    "Historical comparators attest head-directed pouring without zodiac signs (Celsus I.4, Morgan G.74 f12r) and "
                    "periodic non-sign-gated head washing (Regel ch. 22), while the one zodiac-specific head-washing rule on disk "
                    "(I F 35 Aries f24r) FORBIDS washing the head. Furthermore, as Join 3 established, neither zodiac comparators "
                    "(Cgm 7958, Cpg 213/557/291) nor balneal comparators key blue vs green pigment to water temperature."
                ),
            },
        ],
    }


def render_markdown(data: dict) -> str:
    lines = []
    lines.append("# Witness 3 (`w3_zodiac_bath_rules`): Explicit Zodiac-to-Bath Execution Rules & Join 3 Cross-Check")
    lines.append("")
    lines.append("**Scientific & Custody Framing.** MS 408 is not treated as a cipher; no cipher key is sought. Historical comparator procedures are kept strictly separate from MS 408 claims. All sources and SQLite databases were opened strictly read-only. In particular, **Munich BSB Cgm 7958 (`CGM7958_28_MANSION_TRANSLATION_TABLE.tsv`) preserves the `Q-M15` field-alignment qualifier**: bodily marks occupy `predisposition`, water/age risk occupies `diagnostic_marks`, and the modern `treatment_implication` / `herbal_crossref_candidate` / `balneal_crossref_candidate` columns are excluded as unverified hypotheses.")
    lines.append("")
    lines.append("---")
    lines.append("")
    lines.append("## 1. Summary of Extracted Rules on Disk (Task 1)")
    lines.append("")
    rules = data["rules_catalog"]
    by_type = {}
    for r in rules:
        by_type[r["rule_type"]] = by_type.get(r["rule_type"], 0) + 1
    lines.append(f"Total catalogued rule/comparator records: **{len(rules)}** across **{len(data['substrate_manuscripts'])}** substrate-indexed witnesses plus unindexed/composite witnesses (`Prague I F 35`, `Caius 336/725`, `Wellcome MS 549`, `Pol Hs. 3227a`, `Cpg 787`, `Clm 30150`, `Pal. lat. 1257`, `Cgm 7958`, `Dd.6.29`, `Trinity O.7.20`).")
    lines.append("")
    lines.append("- **Explicit Moon-in-sign bathing rules (9 records across 6 distinct witnesses):**")
    lines.append("  1. **German *Regel der Gesundheit* / *Practica* 7-sign tradition** (`Cpg 213 f155r` [1421], `Cpg 213 f170v` [1421], `Cpg 557 f77v` [1468], `Cpg 291 f43v–44r` [1477–1496], `Wellcome MS 438 p.497` [c.1475 copy of 1429+Practica]): All five places list the **exact same 7 favorable Moon-in-sign bathing signs** — **Aries, Taurus, Cancer, Libra, Scorpio, Sagittarius, Pisces** — with `Wellcome MS 438 p.497` specifying *allerbest Im krebs oder im fischen* (**Cancer** or **Pisces**) and `Cpg 213`/`557`/`291` requiring a **waning Moon** (*in dem abnemen*, attr. *Aquario*) for bathing and cupping.")
    lines.append("  2. **Haly's *badstuben* (sweat-bath/bathhouse) avoidance in *hot signs***: `Cpg 213 f155r` and `Cpg 291 f44r` name **4** avoided signs (**Leo, Virgo, Gemini, Capricorn**); `Cpg 213 f170v` names **4** signs (**Leo, Virgo, Capricorn, Aquarius**, swapping Gemini for Aquarius); `Cpg 557 f77v` shortens the list to **2** (**Leo, Capricorn**); `Wellcome MS 438 p.497` states the condition generally (*nit baden in den hitzigen zeichen wenn so man sich artznen wil zuo dem parle vnd zuo fuochten siechtagen*).")
    lines.append("  3. **Prague NK I F 35 (Erfurt, 1431)** preserves two internal witnesses with explicit cross-section referral (`f23r` → `ff24r–28r`): the `f22v` `Balneari` grid row (`m, m, m, B, B, m, m, m, B, o, m, B`) vs `ff24r–28r` prose (`Aries` favorable + head wash barred; `Cancer`, `Sagittarius`, `Aquarius` favorable; `Capricorn` favorable with unread `si non mi...`; `Leo` verse unresolved; `Virgo`/`Libra`/`Aquarius` also embed month-based perilous-days water/bath bans for Aug/Sep/Jan).")
    lines.append("  4. **Cambridge, Gonville & Caius MS 336/725 (`ff128v–130v`)** & **Nuremberg GNM Hs. 3227a (`f68v`)**: Both Moon-in-sign texts explicitly approve bathing only in **Aries** (*to be bathed and stewed* on `Caius 129r`; *balnea tucius intres* on `Pol 68v`) while forbidding head cutting/treatment; Taurus–Pisces carry no bathing clauses.")
    lines.append("- **Lunar mansion nativity water-risk (`Cgm 7958`, `Q-M15` preserved):** `CGM7958_28_MANSION_TRANSLATION_TABLE.tsv` records **birth-mansion** prognostics (*wer dar under geporn wirt*), NOT electional bathing rules. Six entries mention water/weapons hazards in `source_text` (M8, M9, M13, M15, M20, M24). In **M15 (`Algofara` / `Al-Ghafr`, fol. 6v–7r)**, `sal sich hüten vor wassen` sits in `diagnostic_marks` (with marks shifted into `predisposition`), and modern cross-references (`Zone 2`, `f79r`) are unverified hypotheses.")
    lines.append("- **Catalog-attested uninspected table (`Wellcome MS 549 f86v`, 1471):** Catalogued by Moorat as *\"Table of zodiacal signs and corresponding aspects in relation to blood letting, baths, etc.\"* (`blocked-acquisition` in substrate; no primary images on disk).")
    lines.append("- **Non-sign bathing timing gates (6 records):** Month-gated regimens (`Cpg 5 17r–17v`, `Cpg 214 57v–58v`, `Wellcome MS 49 f45r`, `Berlin Ms. germ. fol. 1191 f5r–5v/f16v`), dog-days exclusion (`excepto mense canino` in `Cpg 787 f78v` & `Clm 30150 f36r`), season/tolerance/plague gates (`Wellcome MS 16`, `Casanatense 4182 f102–103`), and post-bloodletting day-6 release (`Pal. lat. 1257 f23r`, `f156r`).")
    lines.append("- **Checked negative witnesses:** `Tübingen Md 2` (`13r` `12×7` grid and `51r–144v` zodiac chapters have 0 bath rules), `Cgm 288` (chapter title *Von dem pade* only), `Clm 8244` (thermal bath prose, no sign-gate extracted), `Morgan M.165`, `Dd.6.29`, and `Trinity O.7.20`.")
    lines.append("")
    lines.append("| Rule ID | Witness & Date | Locus | Input Condition | Gate | Bath Parameter | Routes Across Sections? |")
    lines.append("|---|---|---|---|---|---|---|")
    for r in rules:
        lines.append(
            f"| `{r['rule_id']}` | {r['witness_shelfmark']} | {r['folio_locus']} | {r['input_condition']} | **{r['gate']}** | {r['bath_parameter']} | {'Yes' if r['routes_across_sections'] else 'No'} |"
        )
    lines.append("")
    lines.append("---")
    lines.append("")
    lines.append("## 2. Twelve-Sign Cross-Witness Bathing Matrix (Aries–Pisces, Task 2)")
    lines.append("")
    lines.append("Columns 1–9 are **explicit sign-keyed bathing witnesses** (`Cpg 213 155r`, `Cpg 213 170v`, `Cpg 557 77v`, `Cpg 291 44r`, `Wellcome MS 438 p.497`, `I F 35 22v` grid, `I F 35 24r–28r` prose, `Caius 336/725 128v–130v`, `Pol 3227a 68v`). Column 10 preserves `Cgm 7958` **nativity** water-risk warnings separately (with `Q-M15` explicit) so birth hazards are never conflated with bathing elections; `Wellcome MS 549 f86v` remains `CATALOG_UNINSPECTED` across all 12 signs.")
    lines.append("")
    lines.append("| Sign | Cpg 213 `155r` | Cpg 213 `170v` | Cpg 557 `77v` | Cpg 291 `44r` | MS 438 `p.497` | I F 35 `22v` | I F 35 `24r–28r` | Caius `128v–130v` | Pol `68v` | Tally (Fav/Avoid/Mid/Silent) | Cgm 7958 Nativity Water Risk (Non-Election, `Q-M15`) |")
    lines.append("|---|---|---|---|---|---|---|---|---|---|---|---|")
    for row in data["matrix_12_signs"]:
        t = row["tally_9_election_columns"]
        tally_s = f"{t['favorable_or_qualified']} / {t['explicit_avoid']} / {t['middle']} / {t['silent_omitted_or_unresolved']}"
        lines.append(
            f"| **{row['sign']}** | {row['cpg213_f155r']} | {row['cpg213_f170v']} | {row['cpg557_f77v']} | {row['cpg291_f44r']} | {row['wellcome438_p497']} | {row['if35_f22v_grid']} | {row['if35_ff24r_28r_prose']} | {row['caius336_ff128v_130v']} | {row['pol3227a_f68v']} | `{tally_s}` | {row['cgm7958_nativity_water_risk_non_election']} |"
        )
    lines.append("")
    lines.append("### Key Focal-Sign Findings (Aries, Taurus, Virgo, & M15)")
    lines.append("- **Aries (`8` Favorable / `0` Avoid / `1` Middle / `0` Silent):** Strongest cross-witness bathing consensus (`Cpg 213`, `Cpg 557`, `Cpg 291`, `Wellcome MS 438`, `I F 35` prose/verse, `Caius`, `Pol`; only `I F 35` grid `22v` gives `m`). However, `I F 35 24r`, `Caius 128v–129r`, and `Pol 68v` all **prohibit head washing or head treatment** in Aries.")
    lines.append("- **Taurus (`5` Favorable / `0` Avoid / `1` Middle / `3` Silent):** Approved in the *Regel*/*Practica* 7-sign list (`Cpg 213`, `Cpg 557`, `Cpg 291`, `MS 438`), graded `m` in `I F 35` grid, and silent on bathing in `I F 35` prose, `Caius`, and `Pol`. Never singled out as the top or unique bath sign.")
    lines.append("- **Virgo (`0` Favorable / `3` Avoid / `1` Middle / `5` Silent):** **Never favorable** in any inspected historical witness. Explicitly **AVOID** for bathhouse (*badstuben*) entry in `Cpg 213 155r`, `Cpg 213 170v`, and `Cpg 291 44r` (under Haly's hot-sign rule); `m` in `I F 35 22v` grid with an August water-drowning warning embedded in `26r`; silent in `MS 438` (unless included in *hitzigen zeichen*), `Cpg 557` (shortened 2-sign list), `Caius`, and `Pol`.")
    lines.append("- **Cgm 7958 M15 (`Algofara` / `Al-Ghafr`, fol. 6v–7r, `Q-M15`):** Historical text states a **nativity risk** (`er sal sich hüten vor wassen` — beware water), NOT a bathing election. In the on-disk TSV, marks sit in `predisposition`, water/age risk sits in `diagnostic_marks`, `likely_death_or_risk` reads `[pending]`, and the `Zone 2` / `f79r` columns are unverified modern hypotheses.")
    lines.append("")
    lines.append("---")
    lines.append("")
    lines.append("## 3. Cross-Check Against MS 408 Join 3 Intersections (Task 3)")
    lines.append("")
    cc = data["join3_crosscheck"]
    lines.append(f"**Overall Verdict: `{cc['overall_verdict']}`**")
    lines.append("")
    for a in cc["anchors_checked"]:
        lines.append(f"### {a['ms408_anchor']}")
        lines.append(f"- **MS 408 Observed Facts (Join 3 `REGISTRATION.json`):** " + "; ".join(f"{k}: {v}" for k, v in a["ms408_observed_facts"].items()))
        lines.append(f"- **Cross-Check Verdict:** `{a['cross_check_verdict']}`")
        lines.append(f"- **Assessment:** {a['explanation']}")
        lines.append("")
    lines.append("### Open Limits")
    lines.append("1. **Wellcome MS 549 `f86v`** (`Table of zodiacal signs and corresponding aspects in relation to blood letting, baths, etc.`, 1471) remains `blocked-acquisition` in the substrate DB; its 12 sign cells cannot be checked without primary images.")
    lines.append("2. **Unopened/untranscribed passages** in `Cgm 288` (*Von dem pade*), `Clm 8244` (*Tömlinger Bäderbuch*), `Berlin Ms. germ. fol. 1191` (`ff31r–62v` missing from PDF), and `Tübingen Md 2` (`ff14v–22r` *Regel*) remain outside verified text extraction.")
    lines.append("3. **No MS 408 temperature, clock, or traversal witness** is supplied by these comparators: none maps blue vs green bath pigment to temperature, and none explains why Light Taurus (`f71v.12`) shares 7 complete chip groups (including unique `shldy` and `okol`) with `f83v.P3` while Virgo (`f72v2`) enters only at chip-contiguous scope.")
    lines.append("")
    return "\n".join(lines)


def main():
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    (OUT_DIR / "scripts").mkdir(parents=True, exist_ok=True)

    cgm7958_data = load_cgm7958_water_and_m15()
    w549_cat = load_wellcome549_catalog()
    substrate_mss = load_substrate_metadata()
    if35_grid = load_if35_grid()
    join3 = load_join3_summary()

    rules = build_rules_catalog(cgm7958_data, w549_cat, if35_grid)
    matrix_12 = build_12_sign_matrix(if35_grid, cgm7958_data)
    join3_cc = build_join3_crosscheck(matrix_12, join3)

    all_cited = sorted({p for r in rules for p in r["source_paths"]} | {
        str(SUBSTRATE_DB),
        str(JOIN3_REG),
        str(ZODIAC_USES_JSON),
        str(CGM7958_TSV),
        str(WELLCOME_CAT),
        str(HAUSBUSH_SELECTED_MD),
        str(HAUSBUSH_ACCEPTED_JSON),
        str(CPG557_REF_MD),
        str(CPG213_REF_MD),
    })
    verified_paths = verify_source_paths(all_cited)

    payload = {
        "schema_version": 1,
        "witness_id": "w3_zodiac_bath_rules",
        "title": "Explicit Zodiac-to-Bath Execution Rules in Local Comparators & /manuscripts",
        "generated_utc": datetime.now(timezone.utc).isoformat(),
        "scientific_framing": (
            "MS 408 is not a cipher; no cipher key is sought. Historical comparator rules and "
            "MS 408 structural findings are kept strictly separate. Q-M15 field-alignment qualifier "
            "and unverified-hypothesis exclusions are preserved."
        ),
        "verified_source_paths_count": len(verified_paths),
        "verified_source_paths": verified_paths,
        "substrate_manuscripts": substrate_mss,
        "cgm7958_28_mansions_audit": cgm7958_data,
        "wellcome_ms549_catalog": w549_cat,
        "if35_balneari_grid": if35_grid,
        "rules_catalog": rules,
        "matrix_12_signs": matrix_12,
        "join3_crosscheck": join3_cc,
    }

    rules_json_path = OUT_DIR / "RULES_MATRIX.json"
    rules_json_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

    md_text = render_markdown(payload)
    result_md_path = OUT_DIR / "RESULT.md"
    result_md_path.write_text(md_text, encoding="utf-8")

    # Build RECEIPT.json for all deliverables in w3_zodiac_bath_rules
    tracked_files = [
        OUT_DIR / "scripts" / "run_w3.py",
        rules_json_path,
        result_md_path,
    ]
    files_manifest = []
    for fp in tracked_files:
        files_manifest.append({
            "relative_path": str(fp.relative_to(OUT_DIR)),
            "absolute_path": str(fp),
            "bytes": fp.stat().st_size,
            "sha256": sha256_file(fp),
        })

    receipt = {
        "schema_version": 1,
        "witness_id": "w3_zodiac_bath_rules",
        "output_dir": str(OUT_DIR),
        "generated_utc": datetime.now(timezone.utc).isoformat(),
        "source_paths_verified_count": len(verified_paths),
        "rules_catalog_count": len(rules),
        "matrix_signs_count": len(matrix_12),
        "files": files_manifest,
    }
    receipt_path = OUT_DIR / "RECEIPT.json"
    receipt_path.write_text(json.dumps(receipt, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print(f"Wrote {rules_json_path} ({rules_json_path.stat().st_size} B)")
    print(f"Wrote {result_md_path} ({result_md_path.stat().st_size} B)")
    print(f"Wrote {receipt_path} ({receipt_path.stat().st_size} B)")
    print(f"Verified {len(verified_paths)} cited source paths; {len(rules)} rules; {len(matrix_12)} matrix signs.")


if __name__ == "__main__":
    main()
