#!/usr/bin/env python3
"""Assemble two native full-reading packets into a private synastry dossier.

This adapter intentionally does not interpret a relationship or generate a
pass/fail result. It freezes comparable inputs, derives directional pair
contacts from the two native charts, calls the neutral ``marriage-match``
product, and emits a complete source map for the report writers. Do not write
its input or output into a repository path.
"""

from __future__ import annotations

import argparse
import importlib.util
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Any, Mapping


ROOT = Path(__file__).resolve().parents[3]
SCRIPTS = ROOT / "scripts"
if str(SCRIPTS) not in sys.path:
    sys.path.insert(0, str(SCRIPTS))

from marriage_match import build_marriage_match_dossier  # noqa: E402
from aspects import _calc_pair_aspects  # noqa: E402
from narayana_dasha import _rasi_aspects  # noqa: E402
from relationship_analysis import classify_relationship_event_class  # noqa: E402


SCHEMA = "jyotish.full_synastry_dossier.v1"
PACKET_ADAPTER = Path(__file__).with_name("validate_full_synastry_packets.py")
_SPEC = importlib.util.spec_from_file_location("full_synastry_receipt", PACKET_ADAPTER)
_RECEIPT = importlib.util.module_from_spec(_SPEC)
assert _SPEC and _SPEC.loader
_SPEC.loader.exec_module(_RECEIPT)


MODULE_ROLES = {
    "chart": "primary_natal_structure",
    "functional_benefic_malefic": "primary_natal_structure",
    "bhava_chalit": "primary_natal_structure",
    "aspects": "pair_interaction_contacts",
    "planetary_friendship": "pair_interaction_contacts",
    "house_map": "primary_natal_structure",
    "varga_full": "primary_varga_structure",
    "d9_navamsa_expanded": "primary_varga_structure",
    "vargottama": "primary_varga_structure",
    "lagna_vargottamamsa": "primary_varga_structure",
    "pushkara": "primary_varga_structure",
    "pushkara_planets": "primary_varga_structure",
    "varga_extended": "topic_bounded_varga_context",
    "vimsopaka": "strength_and_weighting",
    "shadbala": "strength_and_weighting",
    "bhava_bala": "strength_and_weighting",
    "ashtakavarga": "strength_and_weighting",
    "dispositor_chains": "strength_and_weighting",
    "final_dispositors": "strength_and_weighting",
    "jaimini": "primary_jaimini_structure",
    "special_lagnas": "primary_jaimini_structure",
    "argala": "primary_jaimini_structure",
    "rashi_tulya_navamsa": "primary_jaimini_structure",
    "dasha": "primary_timing",
    "dasha_sandhi": "primary_timing",
    "narayana_dasha": "primary_timing",
    "nakshatra_dasha": "primary_timing",
    "yogini_dasha": "secondary_timing",
    "ashtottari_dasha": "secondary_timing",
    "kalachakra_dasha": "secondary_timing",
    "navamsha_dasha": "secondary_timing",
    "niryaana_shoola_dasha": "secondary_timing",
    "shastihayani_dasha": "secondary_timing",
    "dasa_convergence": "timing_convergence",
    "rashi_dasha_profile_selection": "timing_profile_boundary",
    "double_transit_pac": "primary_timing",
    "transit_ll7l": "primary_timing",
    "tajika_yogas": "annual_corroboration",
    "tajika": "annual_corroboration",
    "solar_return": "annual_corroboration",
    "muntha": "annual_corroboration",
    "sahams": "annual_corroboration",
    "vivah_saham": "annual_corroboration",
    "tithi_lord": "annual_corroboration",
    "transit_positions": "transit_corroboration",
    "transit_multi_reference": "transit_corroboration",
    "bhrigu_pada_dasha": "parameter_sensitive_timing",
    "marriage_counting": "bounded_context",
    "trimshamsa_d30": "bounded_context",
    "punarphoo": "observation_only",
    "yogas_doshas": "pattern_and_pressure",
    "yoga": "pattern_and_pressure",
    "avasthas": "condition_and_capacity",
    "sensitive_points": "derived_point_context",
    "congregation": "pattern_and_pressure",
    "nakshatra_advanced": "nakshatra_context",
    "kp": "specialized_timing",
    "relationship_strict_evidence": "relationship_book_evidence",
    "unified_western_reading": "separate_western_support",
    "prashna": "question_chart_context",
}


NARRATIVE_ROLE_PLAN = {
    "primary_natal_structure": (
        ("relationship_thesis", "what_each_person_brings"), "primary_narrative_evidence",
    ),
    "pair_interaction_contacts": (
        ("emotional_safety", "attraction_and_closeness", "communication_conflict_and_repair"), "primary_narrative_evidence",
    ),
    "primary_varga_structure": (
        ("what_each_person_brings", "can_it_stay_steady"), "primary_narrative_evidence",
    ),
    "strength_and_weighting": (
        ("relationship_thesis", "can_it_stay_steady", "shared_life_gains_and_pressures"), "weight_or_conflict_check",
    ),
    "primary_jaimini_structure": (
        ("relationship_progression", "can_it_stay_steady"), "primary_narrative_evidence",
    ),
    "primary_timing": (
        ("relationship_progression", "relationship_weather"), "event_class_corroboration",
    ),
    "secondary_timing": (
        ("relationship_weather",), "secondary_corroboration_only",
    ),
    "timing_convergence": (
        ("relationship_weather",), "conflict_or_convergence_check",
    ),
    "timing_profile_boundary": (
        ("relationship_weather",), "parameter_boundary",
    ),
    "annual_corroboration": (
        ("relationship_weather", "relationship_progression"), "event_class_corroboration",
    ),
    "transit_corroboration": (
        ("relationship_weather",), "event_class_corroboration",
    ),
    "parameter_sensitive_timing": (
        ("relationship_weather",), "parameter_sensitive_corroboration",
    ),
    "bounded_context": (
        ("shared_life_gains_and_pressures", "can_it_stay_steady"), "bounded_context_only",
    ),
    "pattern_and_pressure": (
        ("communication_conflict_and_repair", "can_it_stay_steady"), "pressure_context_not_verdict",
    ),
    "condition_and_capacity": (
        ("what_each_person_brings", "can_it_stay_steady"), "condition_check",
    ),
    "derived_point_context": (
        ("relationship_weather",), "supporting_context_only",
    ),
    "nakshatra_context": (
        ("attraction_and_closeness", "relationship_weather"), "supporting_context_only",
    ),
    "specialized_timing": (
        ("relationship_weather",), "specialized_corroboration_only",
    ),
    "relationship_book_evidence": (
        ("relationship_thesis", "relationship_progression", "can_it_stay_steady"), "rule_grounding_only",
    ),
    "separate_western_support": (
        (), "private_supplementary_convergence_only",
    ),
    "question_chart_context": (
        (), "private_supplementary_convergence_only",
    ),
}


RELATIONSHIP_LENSES = (
    {
        "lane": "relationship_state",
        "customer_question": "What is the central state of this relationship now: pull, mismatch, readiness or pause?",
        "required_pair_tasks": (
            "D1/D9 mutual overlays and relationship axes",
            "two-person Dasha/Narayana/Chara context comparison",
        ),
    },
    {
        "lane": "emotional_safety",
        "customer_question": "Do the two people feel emotionally safe, seen and at ease together?",
        "required_pair_tasks": (
            "D1/D9 mutual overlays and relationship axes",
            "lived interaction: emotional safety, attraction, communication and conflict pattern",
        ),
    },
    {
        "lane": "attraction_and_closeness",
        "customer_question": "How do attraction, affection, closeness and personal space develop between them?",
        "required_pair_tasks": (
            "lived interaction: emotional safety, attraction, communication and conflict pattern",
            "long-term intimacy and repair: 5/7/8/12 axes, UL/DK/A7, Argala and pressure layers",
        ),
    },
    {
        "lane": "communication_conflict_and_repair",
        "customer_question": "How do they communicate, disagree, withdraw, reconnect and repair?",
        "required_pair_tasks": (
            "lived interaction: emotional safety, attraction, communication and conflict pattern",
            "long-term intimacy and repair: 5/7/8/12 axes, UL/DK/A7, Argala and pressure layers",
        ),
    },
    {
        "lane": "relationship_progression",
        "customer_question": "What moves the relationship from attraction to partnership, public commitment or legal marriage?",
        "required_pair_tasks": (
            "two-person Dasha/Narayana/Chara context comparison",
            "secondary-dasha convergence and disagreement review",
            "shared transit, Tajika, Saham and annual-window comparison",
        ),
    },
    {
        "lane": "shared_life_gains_and_pressures",
        "customer_question": "What becomes easier together, and where do home, money, work, family or private-space pressures accumulate?",
        "required_pair_tasks": (
            "shared gain and cost: resources, home, work and private-space axes",
            "long-term intimacy and repair: 5/7/8/12 axes, UL/DK/A7, Argala and pressure layers",
        ),
    },
    {
        "lane": "stability_and_long_term_repair",
        "customer_question": "Can the relationship stay steady through responsibility, intimacy and repair?",
        "required_pair_tasks": (
            "DK, UL, UL-second and A7/Darapada cross-comparison",
            "long-term intimacy and repair: 5/7/8/12 axes, UL/DK/A7, Argala and pressure layers",
        ),
    },
    {
        "lane": "near_term_relationship_weather",
        "customer_question": "What relationship stage is most supported in the next usable period?",
        "required_pair_tasks": (
            "two-person Dasha/Narayana/Chara context comparison",
            "shared transit, Tajika, Saham and annual-window comparison",
        ),
    },
)


READER_SECTION_BRIEFS = (
    ("relationship_thesis", "relationship_state", ()),
    ("what_each_person_brings", None, ()),
    ("emotional_safety", "emotional_safety", ("emotional_safety_and_lived_experience",)),
    (
        "attraction_and_closeness",
        "attraction_and_closeness",
        ("attraction_and_closeness", "pressure_conflict_and_recovery"),
    ),
    (
        "communication_conflict_and_repair",
        "communication_conflict_and_repair",
        ("communication_conflict_and_repair", "pressure_conflict_and_recovery"),
    ),
    ("relationship_progression", "relationship_progression", ("relationship_progression_and_commitment",)),
    (
        "shared_life_gains_and_pressures",
        "shared_life_gains_and_pressures",
        ("shared_life_gains_and_pressures", "pressure_conflict_and_recovery"),
    ),
    (
        "can_it_stay_steady",
        "stability_and_long_term_repair",
        ("relationship_progression_and_commitment", "pressure_conflict_and_recovery"),
    ),
    ("relationship_weather", "near_term_relationship_weather", ()),
)

INTERACTION_PLANETS = (
    "Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu",
)
RELATIONSHIP_AXIS_HOUSES = {
    1: "presence_and_first_impression",
    5: "romance_and_play",
    7: "partnership_and_commitment",
    8: "intimacy_and_shared_vulnerability",
    12: "privacy_space_and_recovery",
}


def _reader_topics_for_contact(planet: str | None, house: int | None) -> list[str]:
    """Index raw contacts for report sections without assigning a verdict."""
    topics: set[str] = set()
    if planet in {"Moon", "Venus"} or house in {4, 8, 12}:
        topics.add("emotional_safety_and_lived_experience")
    if planet in {"Venus", "Mars", "Moon"} or house in {5, 7, 8}:
        topics.add("attraction_and_closeness")
    if planet == "Mercury" or house in {3, 6}:
        topics.add("communication_conflict_and_repair")
    if planet in {"Mars", "Saturn", "Rahu", "Ketu"} or house in {6, 8, 12}:
        topics.add("pressure_conflict_and_recovery")
    if planet in {"Jupiter", "Saturn", "Sun"} or house in {2, 4, 10, 11}:
        topics.add("shared_life_gains_and_pressures")
    if planet in {"Jupiter", "Saturn", "Venus"} or house == 7:
        topics.add("relationship_progression_and_commitment")
    return sorted(topics)


def _recipient_experience_evidence(
    overlays_a_to_b: list[dict[str, Any]],
    overlays_b_to_a: list[dict[str, Any]],
    angular_contacts: list[dict[str, Any]],
    rashi_contacts: list[dict[str, Any]],
) -> dict[str, list[dict[str, Any]]]:
    """Keep recipient-side evidence separate so similarity is never assumed."""
    recipients: dict[str, list[dict[str, Any]]] = {"person_a": [], "person_b": []}
    for recipient, overlays in (("person_b", overlays_a_to_b), ("person_a", overlays_b_to_a)):
        for overlay in overlays:
            recipients[recipient].append({
                "evidence_type": "house_overlay",
                "source_direction": overlay["direction"],
                "source_planet": overlay["planet"],
                "recipient_house": overlay["recipient_house"],
                "reader_topics": _reader_topics_for_contact(overlay["planet"], overlay["recipient_house"]),
                "source_path": "pair_interaction_evidence.*_overlays",
            })
    for contact in angular_contacts:
        direction = contact["direction"]
        recipients_for_contact = (
            ("person_a", "person_b") if direction == "mutual_angle"
            else ("person_b",) if direction == "person_a_to_person_b"
            else ("person_a",) if direction == "person_b_to_person_a"
            else ()
        )
        for recipient in recipients_for_contact:
            source_planet = contact["person_a_planet"] if recipient == "person_b" else contact["person_b_planet"]
            recipients[recipient].append({
                "evidence_type": "angular_contact",
                "source_direction": direction,
                "source_planet": source_planet,
                "counterpart_planet": contact["person_b_planet"] if recipient == "person_b" else contact["person_a_planet"],
                "aspect_type": contact["aspect_type"],
                "reader_topics": _reader_topics_for_contact(source_planet, None),
                "source_path": "pair_interaction_evidence.angular_contacts",
            })
    for contact in rashi_contacts:
        direction = contact["direction"]
        recipients_for_contact = (
            ("person_a", "person_b") if direction == "mutual"
            else ("person_b",) if direction == "person_a_to_person_b"
            else ("person_a",)
        )
        for recipient in recipients_for_contact:
            source_planet = contact["person_a_planet"] if recipient == "person_b" else contact["person_b_planet"]
            recipients[recipient].append({
                "evidence_type": "rashi_contact",
                "source_direction": direction,
                "source_planet": source_planet,
                "counterpart_planet": contact["person_b_planet"] if recipient == "person_b" else contact["person_a_planet"],
                "reader_topics": _reader_topics_for_contact(source_planet, None),
                "source_path": "pair_interaction_evidence.jaimini_rashi_contacts",
            })
    return recipients

EVENT_CLASSES = (
    "romantic_activation",
    "relationship_formation",
    "separation_or_reconciliation",
    "public_formalization",
    "legal_marriage",
    "legal_divorce",
)


def _packet(value: Mapping[str, Any]) -> Mapping[str, Any]:
    nested = value.get("raw_full_reading") if isinstance(value, Mapping) else None
    return nested if isinstance(nested, Mapping) else value


def _modules(packet: Mapping[str, Any]) -> Mapping[str, Any]:
    value = packet.get("modules") if isinstance(packet, Mapping) else None
    return value if isinstance(value, Mapping) else {}


def _longitude(value: Any) -> float | None:
    if not isinstance(value, Mapping):
        return None
    for key in ("longitude", "degree_raw", "lon", "degree"):
        candidate = value.get(key)
        if isinstance(candidate, (int, float)) and not isinstance(candidate, bool):
            return float(candidate) % 360.0
    return None


def chart_snapshot(packet: Mapping[str, Any]) -> dict[str, Any]:
    """Extract only the calculated positions required by marriage-match."""
    chart = _modules(packet).get("chart") or packet.get("chart") or {}
    chart = chart if isinstance(chart, Mapping) else {}
    ascendant = chart.get("ascendant") if isinstance(chart.get("ascendant"), Mapping) else {}
    planets = chart.get("planets") if isinstance(chart.get("planets"), Mapping) else {}
    snapshot: dict[str, Any] = {"ascendant": {}, "planets": {}}
    asc_lon = _longitude(ascendant)
    if asc_lon is not None:
        snapshot["ascendant"] = {"longitude": asc_lon}
    for planet in INTERACTION_PLANETS:
        longitude = _longitude(planets.get(planet))
        if longitude is not None:
            snapshot["planets"][planet] = {"longitude": longitude}
    return snapshot


def _house_from_longitudes(longitude: float, ascendant: float) -> int:
    return (int(longitude // 30) - int(ascendant // 30)) % 12 + 1


def _d9_longitude(value: Any) -> float | None:
    """Recover a D9 longitude from native sign-index and intra-sign output."""
    direct = _longitude(value)
    if direct is not None:
        return direct
    if not isinstance(value, Mapping):
        return None
    sign_index = value.get("sign_idx")
    degree_in_sign = value.get("degree_in_sign")
    if (
        isinstance(sign_index, int) and not isinstance(sign_index, bool)
        and 0 <= sign_index < 12
        and isinstance(degree_in_sign, (int, float)) and not isinstance(degree_in_sign, bool)
        and 0.0 <= float(degree_in_sign) < 30.0
    ):
        return (sign_index * 30.0 + float(degree_in_sign)) % 360.0
    return None


def _interaction_positions(packet: Mapping[str, Any], *, division: str = "D1") -> dict[str, Any]:
    """Return calculated D1 or D9 positions needed for pair interaction facts."""
    modules = _modules(packet)
    if division == "D9":
        chart = modules.get("varga_full", {}).get("D9_Navamsa", {})
        longitude_for = _d9_longitude
        source_paths = ["modules.varga_full.D9_Navamsa"]
    else:
        chart = modules.get("chart") or packet.get("chart") or {}
        longitude_for = _longitude
        source_paths = ["modules.chart.ascendant", "modules.chart.planets"]
    chart = chart if isinstance(chart, Mapping) else {}
    asc_key = "Ascendant" if division == "D9" else "ascendant"
    ascendant = chart.get(asc_key) if isinstance(chart.get(asc_key), Mapping) else {}
    planets = chart if division == "D9" else chart.get("planets") if isinstance(chart.get("planets"), Mapping) else {}
    asc_lon = longitude_for(ascendant)
    longitudes = {
        planet: longitude
        for planet in INTERACTION_PLANETS
        if (longitude := longitude_for(planets.get(planet))) is not None
    }
    return {
        "division": division,
        "source_paths": source_paths,
        "ascendant_longitude": asc_lon,
        "planet_longitudes": longitudes,
    }


def _cross_house_overlays(
    source: Mapping[str, Any], recipient: Mapping[str, Any], direction: str,
) -> list[dict[str, Any]]:
    recipient_asc = recipient.get("ascendant_longitude")
    if not isinstance(recipient_asc, (int, float)):
        return []
    overlays = []
    for planet, longitude in source.get("planet_longitudes", {}).items():
        house = _house_from_longitudes(float(longitude), float(recipient_asc))
        overlays.append({
            "direction": direction,
            "planet": planet,
            "planet_longitude": round(float(longitude), 6),
            "recipient_house": house,
            "relationship_axis": RELATIONSHIP_AXIS_HOUSES.get(house),
        })
    return overlays


def _cross_angular_contacts(
    person_a: Mapping[str, Any], person_b: Mapping[str, Any],
) -> list[dict[str, Any]]:
    contacts = []
    for a_planet, a_longitude in person_a.get("planet_longitudes", {}).items():
        for b_planet, b_longitude in person_b.get("planet_longitudes", {}).items():
            for contact in _calc_pair_aspects(a_planet, float(a_longitude), b_planet, float(b_longitude)):
                aspect_type = str(contact.get("type"))
                if aspect_type in {"conjunction", "opposition"}:
                    direction = "mutual_angle"
                elif a_planet != b_planet and aspect_type.startswith(f"{a_planet}_"):
                    direction = "person_a_to_person_b"
                elif a_planet != b_planet and aspect_type.startswith(f"{b_planet}_"):
                    direction = "person_b_to_person_a"
                else:
                    # A same-named pair (for example Mars-to-Mars) cannot be
                    # oriented from the aspect label alone. The native helper
                    # preserves the directed angular distance for special
                    # graha aspects, so use it to recover the source side.
                    directed_from_a = (float(b_longitude) - float(a_longitude)) % 360.0
                    directed_from_b = (float(a_longitude) - float(b_longitude)) % 360.0
                    actual = float(contact.get("actual_diff", -1.0)) % 360.0
                    if abs(actual - directed_from_a) < 0.02:
                        direction = "person_a_to_person_b"
                    elif abs(actual - directed_from_b) < 0.02:
                        direction = "person_b_to_person_a"
                    else:
                        direction = "undetermined_direction"
                contacts.append({
                    "person_a_planet": a_planet,
                    "person_b_planet": b_planet,
                    "direction": direction,
                    "aspect_type": aspect_type,
                    "aspect_degree": contact.get("aspect_degree"),
                    "orb_degrees": contact.get("orb"),
                    "orb_category": contact.get("orb_category"),
                    "strength": contact.get("strength"),
                })
    return contacts


def _cross_rashi_contacts(
    person_a: Mapping[str, Any], person_b: Mapping[str, Any],
) -> list[dict[str, Any]]:
    contacts = []
    for a_planet, a_longitude in person_a.get("planet_longitudes", {}).items():
        a_sign = int(float(a_longitude) // 30) % 12
        for b_planet, b_longitude in person_b.get("planet_longitudes", {}).items():
            b_sign = int(float(b_longitude) // 30) % 12
            a_to_b = _rasi_aspects(a_sign, b_sign)
            b_to_a = _rasi_aspects(b_sign, a_sign)
            if a_to_b or b_to_a:
                contacts.append({
                    "person_a_planet": a_planet,
                    "person_b_planet": b_planet,
                    "person_a_sign_index": a_sign,
                    "person_b_sign_index": b_sign,
                    "direction": "mutual" if a_to_b and b_to_a else "person_a_to_person_b" if a_to_b else "person_b_to_person_a",
                })
    return contacts


def _build_divisional_pair_interaction_evidence(
    person_a: Mapping[str, Any], person_b: Mapping[str, Any],
    *, division: str,
) -> dict[str, Any]:
    """Calculate raw D1/D9 contacts without interpreting compatibility."""
    positions_a = _interaction_positions(person_a, division=division)
    positions_b = _interaction_positions(person_b, division=division)
    has_ascendants = all(
        isinstance(positions.get("ascendant_longitude"), (int, float))
        for positions in (positions_a, positions_b)
    )
    has_planets = bool(positions_a["planet_longitudes"] and positions_b["planet_longitudes"])
    status = "executed" if has_ascendants and has_planets else "blocked"
    overlays_a_to_b = _cross_house_overlays(positions_a, positions_b, "person_a_to_person_b") if has_ascendants else []
    overlays_b_to_a = _cross_house_overlays(positions_b, positions_a, "person_b_to_person_a") if has_ascendants else []
    angular_contacts = _cross_angular_contacts(positions_a, positions_b) if has_planets else []
    rashi_contacts = _cross_rashi_contacts(positions_a, positions_b) if has_planets else []
    return {
        "status": status,
        "division": division,
        "source_paths": positions_a["source_paths"],
        "person_a_to_person_b_overlays": overlays_a_to_b,
        "person_b_to_person_a_overlays": overlays_b_to_a,
        "angular_contacts": angular_contacts,
        "jaimini_rashi_contacts": rashi_contacts,
        "recipient_experience_evidence": _recipient_experience_evidence(
            overlays_a_to_b, overlays_b_to_a, angular_contacts, rashi_contacts,
        ),
        "boundary": (
            f"This is a directional raw-contact layer from {division}, not a compatibility score or a relationship verdict. "
            "Recipient-side topic indexing prevents a false symmetry assumption: each person's felt benefit, cost and response must be written from their own received evidence, then checked against natal structure, D9/Jaimini and timing."
        ),
    }


def build_pair_interaction_evidence(
    person_a: Mapping[str, Any], person_b: Mapping[str, Any],
) -> dict[str, Any]:
    """Calculate separate D1 and D9 pair-contact evidence without a verdict."""
    d1 = _build_divisional_pair_interaction_evidence(person_a, person_b, division="D1")
    d9 = _build_divisional_pair_interaction_evidence(person_a, person_b, division="D9")
    # Retain the D1 keys for existing dossier consumers. D9 remains distinct
    # because it cannot be substituted for the lived D1 interaction layer.
    return {
        **d1,
        "d9_interaction_evidence": d9,
        "division_boundary": (
            "D1 contacts describe the natal interaction field; D9 contacts describe the divisional relationship and commitment field. "
            "Do not average them, overwrite one with the other, or call either a relationship outcome."
        ),
    }


def build_mutual_affection_activation_brief(
    interaction: Mapping[str, Any],
) -> dict[str, Any]:
    """Prepare reciprocal-care evidence without turning it into a love tactic."""
    d9 = interaction.get("d9_interaction_evidence") if isinstance(interaction, Mapping) else None
    d9 = d9 if isinstance(d9, Mapping) else {}
    recipients = {}
    relevant_topics = {
        "emotional_safety_and_lived_experience", "attraction_and_closeness",
        "communication_conflict_and_repair", "pressure_conflict_and_recovery",
        "relationship_progression_and_commitment",
    }
    for recipient in ("person_a", "person_b"):
        d1_rows = (interaction.get("recipient_experience_evidence", {}) or {}).get(recipient, [])
        d9_rows = (d9.get("recipient_experience_evidence", {}) or {}).get(recipient, [])
        recipients[recipient] = {
            "d1_evidence": [
                row for row in d1_rows if isinstance(row, Mapping)
                and any(topic in relevant_topics for topic in row.get("reader_topics", ()))
            ],
            "d9_evidence": [
                row for row in d9_rows if isinstance(row, Mapping)
                and any(topic in relevant_topics for topic in row.get("reader_topics", ()))
            ],
            "writer_obligations": [
                "what the counterpart can do that helps this recipient feel cherished, safe or warmly connected",
                "what interaction condition helps this recipient maintain closeness without losing agency or space",
                "what concrete pattern can leave this recipient pressured, unseen or likely to withdraw",
                "one mutual practice tied to both recipients' evidence, not a tactic for extracting affection",
            ],
        }
    return {
        "status": "executed" if all(recipients[person]["d1_evidence"] for person in recipients) else "blocked",
        "recipients": recipients,
        "boundary": (
            "This supports reciprocal care and observable relationship practices. It does not infer consent, sexuality, fidelity, "
            "or a method for making someone love another person. D1 and D9 evidence remain separate."
        ),
    }


def _inventory(packet: Mapping[str, Any], person: str) -> list[dict[str, str]]:
    rows = []
    for module_id, value in sorted(_modules(packet).items()):
        status = _RECEIPT._status(value)
        rows.append({
            "person": person,
            "module_id": str(module_id),
            "source_path": f"modules.{module_id}",
            "status": status,
            "relationship_role": MODULE_ROLES.get(str(module_id), "retained_unclassified"),
        })
    return rows


def _source_map(receipt: Mapping[str, Any]) -> list[dict[str, Any]]:
    rows = []
    for row in receipt.get("individual_technique_audit", []):
        rows.append({
            "kind": "individual_technique",
            "label": row.get("technique"),
            "status": row.get("status"),
            "source_path": [
                (row.get("person_a") or {}).get("source_path"),
                (row.get("person_b") or {}).get("source_path"),
            ],
            "person_a_source": (row.get("person_a") or {}).get("source_path"),
            "person_b_source": (row.get("person_b") or {}).get("source_path"),
            "report_use": "compare before narrative",
        })
    for row in receipt.get("pair_execution_tasks", []):
        rows.append({
            "kind": "pair_comparison",
            "label": row.get("task"),
            "status": row.get("status"),
            "source_inputs": row.get("required_inputs", []),
            "report_use": row.get("boundary"),
        })
    return rows


def _module_narrative_plan(packet: Mapping[str, Any], person: str) -> list[dict[str, Any]]:
    """Map every computed source module to a reader question or private boundary."""
    rows = []
    for module_id, value in sorted(_modules(packet).items()):
        role = MODULE_ROLES.get(str(module_id), "retained_unclassified")
        sections, disposition = NARRATIVE_ROLE_PLAN.get(
            role, ((), "private_review_required_before_omission"),
        )
        rows.append({
            "person": person,
            "module_id": str(module_id),
            "source_path": f"modules.{module_id}",
            "status": _RECEIPT._status(value),
            "relationship_role": role,
            "reader_sections": list(sections),
            "disposition": disposition,
        })
    return rows


def _relationship_lens_status(receipt: Mapping[str, Any]) -> list[dict[str, Any]]:
    """Expose complete pair-evidence readiness by reader-relevant question."""
    task_status = {
        str(row.get("task")): str(row.get("status"))
        for row in receipt.get("pair_execution_tasks", [])
        if isinstance(row, Mapping)
    }
    lenses = []
    for definition in RELATIONSHIP_LENSES:
        tasks = list(definition["required_pair_tasks"])
        statuses = {task: task_status.get(task, "blocked") for task in tasks}
        if any(status == "blocked" for status in statuses.values()):
            status = "blocked"
        elif any(status == "parameter_sensitive" for status in statuses.values()):
            status = "parameter_sensitive"
        elif all(status == "ready_for_comparison" for status in statuses.values()):
            status = "ready_for_comparison"
        else:
            status = "not_applicable"
        lenses.append({
            "lane": definition["lane"],
            "customer_question": definition["customer_question"],
            "status": status,
            "required_pair_tasks": statuses,
            "boundary": "Read both people separately, then compare direction, benefit, cost and condition. This is evidence readiness, not a relationship verdict.",
        })
    return lenses


def _recipient_rows_for_topics(
    interaction: Mapping[str, Any], topics: tuple[str, ...],
) -> dict[str, list[dict[str, Any]]]:
    """Select private recipient-side evidence without collapsing directions."""
    by_recipient = interaction.get("recipient_experience_evidence")
    by_recipient = by_recipient if isinstance(by_recipient, Mapping) else {}
    selected: dict[str, list[dict[str, Any]]] = {}
    for recipient in ("person_a", "person_b"):
        rows = by_recipient.get(recipient, [])
        selected[recipient] = [
            row for row in rows
            if isinstance(row, Mapping)
            and any(topic in row.get("reader_topics", ()) for topic in topics)
        ]
    return selected


def build_reader_section_brief(
    narrative_plan: list[dict[str, Any]],
    lenses: list[dict[str, Any]],
    interaction: Mapping[str, Any],
    mutual_affection: Mapping[str, Any],
    timing: Mapping[str, Any],
    event_gate: Mapping[str, Any],
) -> list[dict[str, Any]]:
    """Make every reader section traceable to private evidence before prose."""
    lens_by_lane = {str(row.get("lane")): row for row in lenses if isinstance(row, Mapping)}
    d9 = interaction.get("d9_interaction_evidence")
    d9 = d9 if isinstance(d9, Mapping) else {}
    rows: list[dict[str, Any]] = []
    for section, lens_lane, topics in READER_SECTION_BRIEFS:
        source_modules = [
            {
                "person": row["person"],
                "module_id": row["module_id"],
                "source_path": row["source_path"],
                "status": row["status"],
                "disposition": row["disposition"],
            }
            for row in narrative_plan
            if section in row.get("reader_sections", ())
        ]
        lens = lens_by_lane.get(lens_lane) if lens_lane else None
        row: dict[str, Any] = {
            "section": section,
            "status": lens.get("status") if isinstance(lens, Mapping) else "source_bounded",
            "source_modules": source_modules,
            "pair_lens": lens,
            "boundary": (
                "Use only as a private evidence-selection brief. Write each person's received experience separately; "
                "source availability is not a positive relationship conclusion."
            ),
        }
        if topics:
            row["d1_recipient_evidence"] = _recipient_rows_for_topics(interaction, topics)
            row["d9_recipient_evidence"] = _recipient_rows_for_topics(d9, topics)
        if section == "attraction_and_closeness":
            row["reciprocal_care"] = mutual_affection
        if section == "relationship_weather":
            row["parallel_personal_timing"] = timing
            row["event_resonance_gate"] = event_gate
        rows.append(row)
    return rows


def _parse_period_boundary(value: Any) -> datetime | None:
    """Parse an engine-emitted period boundary without manufacturing one."""
    if not isinstance(value, str) or not value.strip():
        return None
    try:
        return datetime.fromisoformat(value)
    except ValueError:
        try:
            return datetime.strptime(value, "%Y-%m-%d")
        except ValueError:
            return None


def _period_boundary_record(
    period: Any,
    *,
    system: str,
    level: str,
    source_path: str,
) -> dict[str, Any] | None:
    """Keep a dated native period only when both engine boundaries are usable."""
    if not isinstance(period, Mapping):
        return None
    start_raw = period.get("start_datetime") or period.get("start")
    end_raw = period.get("end_datetime") or period.get("end")
    start, end = _parse_period_boundary(start_raw), _parse_period_boundary(end_raw)
    if start is None or end is None or start >= end:
        return None
    label = period.get("lord") or period.get("sign")
    if not isinstance(label, str) or not label:
        return None
    return {
        "system": system,
        "level": level,
        "label": label,
        "start": start.isoformat(timespec="seconds"),
        "end": end.isoformat(timespec="seconds"),
        "source_path": source_path,
    }


def _current_vimshottari_periods(packet: Mapping[str, Any]) -> dict[str, Any]:
    """Read the engine's active MD/AD/PD boundaries; never rebuild Dasha order."""
    dasha = _modules(packet).get("dasha")
    if not isinstance(dasha, Mapping):
        return {"status": "blocked", "reason": "modules.dasha_missing", "periods": []}
    current = dasha.get("current_dasha")
    if not isinstance(current, Mapping):
        return {"status": "blocked", "reason": "current_dasha_missing", "periods": []}
    periods: list[dict[str, Any]] = []
    md = _period_boundary_record(
        current,
        system="vimshottari",
        level="mahadasha",
        source_path="modules.dasha.current_dasha",
    )
    if md:
        periods.append(md)
    ad = current.get("antardasha")
    if not isinstance(ad, Mapping):
        ad = next(
            (
                item for item in current.get("antardasha_timeline", [])
                if isinstance(item, Mapping) and item.get("is_current")
            ),
            None,
        )
    ad_record = _period_boundary_record(
        ad,
        system="vimshottari",
        level="antardasha",
        source_path="modules.dasha.current_dasha.antardasha",
    )
    if ad_record:
        periods.append(ad_record)
    pd = None
    if isinstance(ad, Mapping):
        pd = next(
            (
                item for item in ad.get("pratyantar_dasha_timeline", [])
                if isinstance(item, Mapping) and item.get("is_current")
            ),
            None,
        )
    pd_record = _period_boundary_record(
        pd,
        system="vimshottari",
        level="pratyantar",
        source_path="modules.dasha.current_dasha.antardasha.pratyantar_dasha_timeline",
    )
    if pd_record:
        periods.append(pd_record)
    return {
        "status": "executed" if periods else "blocked",
        "reason": None if periods else "current_dasha_has_no_valid_dated_period",
        "reference_date": dasha.get("reference_date"),
        "periods": periods,
    }


def build_parallel_timing_context(
    person_a: Mapping[str, Any], person_b: Mapping[str, Any],
) -> dict[str, Any]:
    """Preserve two active period contexts without treating calendar overlap as resonance."""
    timing_a = _current_vimshottari_periods(person_a)
    timing_b = _current_vimshottari_periods(person_b)
    status = "executed" if timing_a["periods"] and timing_b["periods"] else "blocked"
    references = {timing_a.get("reference_date"), timing_b.get("reference_date")} - {None}
    return {
        "status": status,
        "reference_dates": {"person_a": timing_a.get("reference_date"), "person_b": timing_b.get("reference_date")},
        "reference_alignment": "matched" if len(references) == 1 else "different_or_missing",
        "person_a_active_periods": timing_a["periods"],
        "person_b_active_periods": timing_b["periods"],
        "systems": {
            "vimshottari": {
                "person_a": timing_a["status"],
                "person_b": timing_b["status"],
                "source_paths": ["modules.dasha.current_dasha", "modules.dasha.current_dasha.antardasha"],
            },
            "narayana": {
                "status": "not_used_for_date_intersection",
                "reason": "native full-reading packet supplies sign-period structure but not absolute start/end dates for this comparison adapter",
            },
        },
        "event_resonance_requirement": {
            "status": "not_established_by_parallel_periods",
            "required_for_any_event_class": [
                "an explicit event class: romantic_activation, relationship_formation, separation, public_formalization, legal_marriage or legal_divorce",
                "both people have the event-class-relevant natal and D9/UL/DK/A7 promise assessed",
                "both people have separately activated event-class timing, not merely concurrent calendar dates",
                "the pair interaction and the relevant transit/annual evidence converge",
                "current relationship status or event history is supplied where the question depends on it",
            ],
        },
        "boundary": (
            "The two date ranges are separate personal contexts. Never calculate or present their calendar overlap as a shared relationship window, "
            "emotional resonance, equal benefit/cost, or evidence that a relationship will begin, separate, reconcile, commit, marry or divorce. "
            "A relationship-event judgment requires the explicit event class and all listed resonance requirements."
        ),
    }


def _strict_stage_status(value: Any) -> str:
    """Normalize the strict-workflow state without upgrading weak evidence."""
    if not isinstance(value, Mapping):
        return "missing"
    raw = str(value.get("status", "")).strip().lower()
    if raw in {"present", "used", "executed", "available"}:
        return "present"
    if raw in {"weak", "partial", "parameter_sensitive", "observation_only"}:
        return "parameter_sensitive"
    return "missing"


def _darakaraka(packet: Mapping[str, Any]) -> str | None:
    jaimini = _modules(packet).get("jaimini")
    jaimini = jaimini if isinstance(jaimini, Mapping) else {}
    for path in (
        ("chara_karaka_standard", "karakas", "DK"),
        ("chara_karaka_8", "karaka_table_8", "Darakaraka"),
        ("chara_karaka_7", "karaka_table", "Darakaraka"),
    ):
        value: Any = jaimini
        for key in path:
            value = value.get(key) if isinstance(value, Mapping) else None
        planet = value.get("planet") if isinstance(value, Mapping) else None
        if isinstance(planet, str) and planet:
            return planet
    return None


def _native_event_candidate(packet: Mapping[str, Any]) -> dict[str, Any]:
    """Invoke the existing native classifier; retain its observation boundary."""
    modules = _modules(packet)
    chart = modules.get("chart")
    chart = chart if isinstance(chart, Mapping) else {}
    planets = chart.get("planets") if isinstance(chart.get("planets"), Mapping) else {}
    ascendant = chart.get("ascendant") if isinstance(chart.get("ascendant"), Mapping) else {}
    asc_sign = ascendant.get("sign")
    dasha = modules.get("dasha")
    dasha = dasha if isinstance(dasha, Mapping) else {}
    current_dasha = dasha.get("current_dasha")
    special_lagnas = modules.get("special_lagnas")
    special_lagnas = special_lagnas if isinstance(special_lagnas, Mapping) else {}
    ul = special_lagnas.get("Upapada_Lagna")
    ul_sign = ul.get("sign") if isinstance(ul, Mapping) else None
    transits = modules.get("transit_positions")
    transits = transits if isinstance(transits, Mapping) else {}
    transit_planets = transits.get("planets") if isinstance(transits.get("planets"), Mapping) else {}
    saturn = transit_planets.get("Saturn") if isinstance(transit_planets.get("Saturn"), Mapping) else {}
    venus = transit_planets.get("Venus") if isinstance(transit_planets.get("Venus"), Mapping) else {}
    if not planets or not isinstance(asc_sign, str) or not isinstance(current_dasha, Mapping):
        return {"status": "blocked", "reason": "chart_or_current_dasha_missing", "event_class": None}
    result = classify_relationship_event_class(
        dict(planets),
        asc_sign=asc_sign,
        dasha_info=dict(current_dasha),
        ul_sign=ul_sign if isinstance(ul_sign, str) else None,
        darakaraka=_darakaraka(packet),
        transit_saturn_longitude=_longitude(saturn),
        transit_venus_longitude=_longitude(venus),
    )
    return {
        "status": str(result.get("claim_status") or "observation_only"),
        "event_class": result.get("event_class") if result.get("event_class") in EVENT_CLASSES else None,
        "active_classes": result.get("active_classes") if isinstance(result.get("active_classes"), list) else [],
        "source_path": "native:relationship_analysis.classify_relationship_event_class",
        "result": result,
    }


def _individual_event_evidence(packet: Mapping[str, Any]) -> dict[str, Any]:
    """Read explicit event evidence while rejecting generic single-chart scores."""
    strict = _modules(packet).get("relationship_strict_evidence")
    if not isinstance(strict, Mapping):
        return {
            "status": "blocked",
            "reason": "modules.relationship_strict_evidence_missing",
            "event_class": None,
        }
    judgement = strict.get("event_judgement")
    judgement = judgement if isinstance(judgement, Mapping) else {}
    contract = strict.get("prediction_boundary_contract")
    contract = contract if isinstance(contract, Mapping) else {}
    declared = judgement.get("event_class") or judgement.get("dominant_label")
    declared_event_class = declared if declared in EVENT_CLASSES else None
    native_candidate = _native_event_candidate(packet)
    native_event_class = native_candidate.get("event_class")
    event_class = declared_event_class or native_event_class
    stages = {
        stage: _strict_stage_status(contract.get(stage))
        for stage in ("promise", "activation", "manifestation", "label")
    }
    if declared_event_class and all(state == "present" for state in stages.values()):
        status = "event_specific_evidence_present"
    elif native_event_class:
        status = "event_class_observation_only"
    elif any(state != "missing" for state in stages.values()):
        status = "event_class_not_established"
    else:
        status = "blocked"
    return {
        "status": status,
        "event_class": event_class,
        "event_class_source": (
            "strict_event_label" if declared_event_class else "native_observation_only" if native_event_class else None
        ),
        "native_event_candidate": native_candidate,
        "stages": stages,
        "source_paths": [
            "modules.relationship_strict_evidence.event_judgement",
            "modules.relationship_strict_evidence.prediction_boundary_contract",
        ],
        "ignored_non_event_fields": {
            "verdict": judgement.get("verdict"),
            "score": judgement.get("score"),
            "reason": "A generic single-chart score or window verdict is not an explicit relationship-event class and cannot establish pair resonance.",
        },
    }


def build_event_resonance_gate(
    person_a: Mapping[str, Any], person_b: Mapping[str, Any],
) -> dict[str, Any]:
    """Record whether a named event may be assessed, never whether it occurred."""
    evidence_a = _individual_event_evidence(person_a)
    evidence_b = _individual_event_evidence(person_b)
    rows = []
    for event_class in EVENT_CLASSES:
        a_matches = evidence_a.get("event_class") == event_class
        b_matches = evidence_b.get("event_class") == event_class
        both_specific = (
            evidence_a.get("status") == "event_specific_evidence_present"
            and evidence_b.get("status") == "event_specific_evidence_present"
        )
        both_observation = (
            evidence_a.get("status") == "event_class_observation_only"
            and evidence_b.get("status") == "event_class_observation_only"
        )
        if a_matches and b_matches and both_specific:
            status = "candidate_alignment_requires_event_history"
        elif a_matches and b_matches and both_observation:
            status = "parallel_observation_only"
        elif a_matches or b_matches:
            status = "one_sided_or_incomplete"
        else:
            status = "not_established"
        rows.append({
            "event_class": event_class,
            "status": status,
            "person_a_event_class": evidence_a.get("event_class"),
            "person_b_event_class": evidence_b.get("event_class"),
            "required_before_any_resonance_claim": [
                "both people independently meet the event-specific promise, activation, manifestation and label gates",
                "the pair interaction and relevant transit/annual evidence converge for the same event class",
                "the real relationship state or dated event history is supplied when claiming that an event occurred",
            ],
        })
    return {
        "status": "executed" if evidence_a.get("status") != "blocked" and evidence_b.get("status") != "blocked" else "blocked",
        "person_a": evidence_a,
        "person_b": evidence_b,
        "event_classes": rows,
        "boundary": (
            "This gate never asserts that two people share an event. It rejects generic single-chart scores and requires a named event class. "
            "Even a candidate alignment requires pair interaction, transit/annual corroboration and real history before reporting a relationship event as having occurred."
        ),
    }


def build_full_synastry_dossier(
    person_a: Mapping[str, Any],
    person_b: Mapping[str, Any],
    *,
    profile_id: str = "practitioner_consensus_v1",
) -> dict[str, Any]:
    """Build a non-narrative delivery packet for the full synastry Skill."""
    packet_a, packet_b = _packet(person_a), _packet(person_b)
    receipt = _RECEIPT.build_execution_receipt(packet_a, packet_b)
    snapshot_a, snapshot_b = chart_snapshot(packet_a), chart_snapshot(packet_b)
    pair_interaction_evidence = build_pair_interaction_evidence(packet_a, packet_b)
    mutual_affection_activation = build_mutual_affection_activation_brief(pair_interaction_evidence)
    parallel_timing_context = build_parallel_timing_context(packet_a, packet_b)
    event_resonance_gate = build_event_resonance_gate(packet_a, packet_b)
    module_narrative_plan = (
        _module_narrative_plan(packet_a, "person_a")
        + _module_narrative_plan(packet_b, "person_b")
    )
    relationship_lenses = _relationship_lens_status(receipt)
    reader_section_brief = build_reader_section_brief(
        module_narrative_plan,
        relationship_lenses,
        pair_interaction_evidence,
        mutual_affection_activation,
        parallel_timing_context,
        event_resonance_gate,
    )
    required = ("Moon", "Venus", "Mars")
    snapshot_ready = all(
        snapshot.get("ascendant") and all(planet in snapshot.get("planets", {}) for planet in required)
        for snapshot in (snapshot_a, snapshot_b)
    )
    product: dict[str, Any]
    if snapshot_ready:
        product = build_marriage_match_dossier(
            snapshot_a,
            snapshot_b,
            relationship_type="romantic_or_marriage",
            profile_id=profile_id,
        )
    else:
        product = {
            "status": "blocked",
            "reason": "chart_snapshot_missing_ascendant_moon_venus_or_mars",
            "boundary": "The matching layer is absent; do not substitute a legacy score or infer it from prose.",
        }
    primary_tasks = {
        "D1/D9 mutual overlays and relationship axes",
        "DK, UL, UL-second and A7/Darapada cross-comparison",
        "two-person Dasha/Narayana/Chara context comparison",
    }
    primary_ready = all(
        row.get("status") == "ready_for_comparison"
        for row in receipt.get("pair_execution_tasks", [])
        if row.get("task") in primary_tasks
    )
    return {
        "schema": SCHEMA,
        "calculation_profile": receipt["calculation_profile"],
        "profile_gate": receipt["profile_gate"],
        "delivery_readiness": "ready_for_narrative" if receipt["profile_gate"] == "passed" and primary_ready else "blocked",
        "delivery_readiness_reason": (
            "both chart profiles match and all primary pair lanes have comparable inputs"
            if receipt["profile_gate"] == "passed" and primary_ready
            else "resolve the profile gate and every primary pair-comparison input before writing a full conclusion"
        ),
        "execution_receipt": receipt,
        "marriage_match": product,
        "chart_snapshots": {"person_a": snapshot_a, "person_b": snapshot_b},
        "pair_interaction_evidence": pair_interaction_evidence,
        "mutual_affection_activation": mutual_affection_activation,
        "parallel_timing_context": parallel_timing_context,
        "event_resonance_gate": event_resonance_gate,
        "module_inventory": _inventory(packet_a, "person_a") + _inventory(packet_b, "person_b"),
        "module_narrative_plan": module_narrative_plan,
        "source_map": _source_map(receipt),
        "relationship_lenses": relationship_lenses,
        "reader_section_brief": reader_section_brief,
        "writing_contract": "skills/jyotish-full-synastry-reading/references/chinese-synastry-writing-contract.md",
        "privacy_boundary": "Private runtime artifact only. Do not commit input packets, dossier output, labels, birth data or relationship history.",
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="Build a private full-synastry evidence dossier from two full-reading packets.")
    parser.add_argument("--person-a", required=True, help="Private JSON full-reading or customer export packet for person A")
    parser.add_argument("--person-b", required=True, help="Private JSON full-reading or customer export packet for person B")
    parser.add_argument("--profile", default="practitioner_consensus_v1", choices=("practitioner_consensus_v1", "raman_muhurtha_v1"))
    parser.add_argument("--output", help="Private output path. Never use a repository directory.")
    args = parser.parse_args()
    with Path(args.person_a).open(encoding="utf-8") as handle:
        person_a = json.load(handle)
    with Path(args.person_b).open(encoding="utf-8") as handle:
        person_b = json.load(handle)
    dossier = build_full_synastry_dossier(person_a, person_b, profile_id=args.profile)
    encoded = json.dumps(dossier, ensure_ascii=False, indent=2)
    if args.output:
        Path(args.output).write_text(encoded + "\n", encoding="utf-8")
    else:
        print(encoded)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
