#!/usr/bin/env python3
"""Create a privacy-safe execution receipt for two full-reading packets.

This is deliberately an audit adapter, not an interpreter.  It establishes
whether both people were calculated under comparable settings and whether the
relationship route's individual evidence modules are actually present before a
synastry narrative is written.
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any, Mapping


SCHEMA = "jyotish.full_synastry_execution_receipt.v1"

# The paths are the native full-reading outputs.  Several technique labels
# intentionally share a producer because one calculation supports more than
# one relationship question; the report writer must still account for each.
REQUIRED_TECHNIQUES: tuple[tuple[str, tuple[str, ...], str], ...] = (
    ("D1/Rashi", ("chart",), "natal promise and house framework"),
    ("Functional Benefic/Malefic", ("functional_benefic_malefic",), "Lagna-specific roles"),
    ("Bhava Chalit", ("bhava_chalit",), "house-boundary confirmation"),
    ("Planetary Aspects", ("aspects",), "actual contact and friction channels"),
    ("Planetary Friendship", ("planetary_friendship",), "planetary cooperation context"),
    ("D9/Navamsa", ("varga_full.D9_Navamsa", "d9_navamsa_expanded"), "long-term relationship structure"),
    ("Vimshottari", ("dasha",), "primary planet-period timing"),
    ("Dasha Sandhi", ("dasha_sandhi",), "period-transition pressure"),
    ("Narayana Dasha", ("narayana_dasha",), "rashi-period cross-check"),
    ("Jaimini/Chara", ("jaimini",), "karakas, arudhas and rashi timing"),
    ("Darakaraka (DK)", ("jaimini",), "partner significator"),
    ("Upapada Lagna (UL)", ("special_lagnas", "yogas_doshas"), "marriage formation and sustenance"),
    ("Argala", ("argala",), "support and obstruction"),
    ("Shadbala", ("shadbala",), "relative planetary strength"),
    ("Ashtakavarga", ("ashtakavarga",), "transit capacity"),
    ("Vimsopaka", ("vimsopaka",), "cross-varga dignity weighting"),
    ("Vargottama", ("vargottama",), "D1-D9 reinforcement"),
    ("Pushkara", ("pushkara",), "supportive Navamsa condition"),
    ("Dispositor Chain", ("dispositor_chains", "final_dispositors"), "energy-flow resolution"),
    ("Inter-chart Linkage", ("inter_chart_linkage",), "D1-D9 linkage within each chart"),
    ("Avasthas", ("avasthas",), "condition and capacity of relationship significators"),
    ("Bhava Bala", ("bhava_bala",), "relative capacity of relationship and shared-life houses"),
    ("Sensitive Points", ("sensitive_points",), "derived point context; never a standalone verdict"),
    ("Lagna Vargottamamsa", ("lagna_vargottamamsa",), "D1-D9 ascendant reinforcement"),
    ("Extended Vargas", ("varga_extended",), "D5/D6/D8/D11 context; use only by documented topic"),
    ("Tajika Yogas", ("tajika_yogas",), "annual activation context"),
    ("Vivah and other Sahams", ("sahams",), "event-sensitive points"),
    ("Mangal Dosha", ("yogas_doshas",), "Mars-only marriage-pressure evidence"),
    ("Punarphoo", ("punarphoo",), "observation-only Moon-Saturn layer"),
    ("Arudha Lagna", ("special_lagnas", "yogas_doshas"), "public relationship frame"),
    ("Tithi Lord", ("tithi_lord",), "lunar relationship context"),
    ("Rashi Tulya Navamsa", ("rashi_tulya_navamsa",), "D1-D9 comparison"),
    ("Marriage Counting", ("marriage_counting",), "supplemental relationship-pattern layer"),
    ("D30 Trimshamsa", ("trimshamsa_d30",), "crisis-pressure context only"),
    ("Muntha / Solar Return", ("muntha", "solar_return"), "annual relationship weather"),
    ("Bhrigu Pada Dasha", ("bhrigu_pada_dasha",), "parameter-sensitive comparison layer"),
    ("Nakshatra Advanced", ("nakshatra_dasha", "nakshatra_advanced"), "nakshatra timing/context"),
    ("Double Transit / LL7L", ("double_transit_pac", "transit_ll7l"), "reference-date activation"),
    ("Transit Multi-reference", ("transit_positions", "transit_multi_reference"), "cross-reference present activation"),
    ("KP 7th-house layer", ("kp",), "formalisation question support"),
    ("Sudarshana Chakra", ("sudarshana",), "triple-lagna confirmation"),
    ("Yogini Dasha", ("yogini_dasha",), "secondary timing only; retain its own birth-balance boundary"),
    ("Ashtottari Dasha", ("ashtottari_dasha",), "conditional secondary timing; verify applicability"),
    ("Kalachakra Dasha", ("kalachakra_dasha",), "conditional secondary timing; verify method profile"),
    ("Navamsha Dasha", ("navamsha_dasha",), "D9-oriented secondary timing; parameter-sensitive"),
    ("Niryaana Shoola Dasha", ("niryaana_shoola_dasha",), "specialized secondary timing; do not lead conclusions"),
    ("Shastihayani Dasha", ("shastihayani_dasha",), "conditional secondary timing; applicability required"),
    ("Dasha Convergence", ("dasa_convergence",), "cross-dasha agreement within each chart"),
    ("Relationship Strict Evidence", ("relationship_strict_evidence",), "relationship-route rule and book-evidence payload"),
    ("Western comparison layer", ("unified_western_reading",), "independent supporting lens"),
)

PAIR_TASKS: tuple[tuple[str, tuple[str, ...], str], ...] = (
    (
        "D1/D9 mutual overlays and relationship axes",
        ("chart", "varga_full.D9_Navamsa"),
        "primary Jyotish pair structure",
    ),
    (
        "lived interaction: emotional safety, attraction, communication and conflict pattern",
        ("chart", "aspects", "planetary_friendship", "varga_full.D9_Navamsa"),
        "compare mutual Lagna/Moon/Venus/Mars/Mercury contacts and D9 confirmation; write observable interaction, not personality labels",
    ),
    (
        "shared gain and cost: resources, home, work and private-space axes",
        ("chart", "varga_full.D2_Hora", "varga_full.D4_Chaturthamsa", "varga_full.D10_Dasamsa", "bhava_bala", "ashtakavarga"),
        "compare 2/4/6/10/11/12-house capacity and relevant varga context; no financial prediction from compatibility alone",
    ),
    (
        "long-term intimacy and repair: 5/7/8/12 axes, UL/DK/A7, Argala and pressure layers",
        ("chart", "jaimini", "special_lagnas", "argala", "yogas_doshas", "trimshamsa_d30"),
        "separate attraction, commitment, deep binding, recovery and pressure; D30 is bounded context only",
    ),
    (
        "DK, UL, UL-second and A7/Darapada cross-comparison",
        ("jaimini", "special_lagnas"),
        "primary Jaimini marriage structure",
    ),
    (
        "two-person Dasha/Narayana/Chara context comparison",
        ("dasha", "narayana_dasha", "jaimini"),
        "primary timing convergence",
    ),
    (
        "secondary-dasha convergence and disagreement review",
        ("nakshatra_dasha", "yogini_dasha", "ashtottari_dasha", "kalachakra_dasha", "navamsha_dasha", "dasa_convergence"),
        "secondary systems qualify or challenge a primary timing window; never invent a date when profiles conflict",
    ),
    (
        "shared transit, Tajika, Saham and annual-window comparison",
        ("tajika_yogas", "sahams", "muntha"),
        "annual and transit corroboration",
    ),
    (
        "international Ashtakoota core, additional Kutas, Mars-only Kuja and separate Papasamya",
        ("chart",),
        "limited Moon/nakshatra and pressure context; build through marriage-match",
    ),
    (
        "Nakshatra relationship context",
        ("nakshatra_dasha",),
        "Jyotish nakshatra context; never a standalone marriage verdict",
    ),
    (
        "optional 27-nakshatra Shukuyo narrative layer",
        (),
        "separate cultural narrative only; never merge into Jyotish evidence",
    ),
    (
        "optional Western synastry/composite/Davison layer",
        ("unified_western_reading",),
        "separate supporting perspective; a natal Western packet is not a composite chart",
    ),
    (
        "Prashna context when a real question chart was supplied",
        (),
        "guarded context only; never replace the two natal charts",
    ),
)


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 _get_path(value: Mapping[str, Any], dotted: str) -> Any:
    cursor: Any = value
    for key in dotted.split("."):
        if not isinstance(cursor, Mapping) or key not in cursor:
            return None
        cursor = cursor[key]
    return cursor


def _status(value: Any) -> str:
    if value is None:
        return "blocked"
    if isinstance(value, Mapping):
        state = str(value.get("execution_status") or value.get("status", "")).lower()
        if state in {"blocked", "not_available", "unavailable", "skipped"}:
            return "blocked"
        if state in {
            "partial", "partial_verified", "parameter_sensitive", "observation_only",
            "guarded", "reference_only", "computed_pending_validation",
        }:
            return "parameter_sensitive"
        if value.get("skipped") is True or value.get("available") is False:
            return "blocked"
    return "executed"


def _profile(packet: Mapping[str, Any]) -> dict[str, Any]:
    birth = packet.get("birth_info", {}) if isinstance(packet.get("birth_info"), Mapping) else {}
    profile = packet.get("calculation_profile", {}) if isinstance(packet.get("calculation_profile"), Mapping) else {}
    settings = profile.get("effective_settings", {}) if isinstance(profile.get("effective_settings"), Mapping) else {}
    return {
        "ayanamsa": birth.get("ayanamsa_name") or birth.get("ayanamsa") or profile.get("ayanamsa") or settings.get("ayanamsa"),
        "node_mode": birth.get("node_mode") or profile.get("node_mode") or settings.get("node_mode"),
        "position_mode": profile.get("position_mode") or settings.get("position_mode"),
        "house_system": profile.get("house_system") or settings.get("house_system"),
    }


def _technique_row(packet: Mapping[str, Any], definition: tuple[str, tuple[str, ...], str]) -> dict[str, Any]:
    label, candidates, purpose = definition
    modules = packet.get("modules", {}) if isinstance(packet.get("modules"), Mapping) else {}
    found_path = next((path for path in candidates if _get_path(modules, path) is not None), None)
    value = _get_path(modules, found_path) if found_path else None
    return {
        "technique": label,
        "status": _status(value),
        "source_path": f"modules.{found_path}" if found_path else None,
        "purpose": purpose,
    }


def _pair_task_row(
    person_a: Mapping[str, Any],
    person_b: Mapping[str, Any],
    definition: tuple[str, tuple[str, ...], str],
) -> dict[str, Any]:
    """State whether both packets can support a comparison, not its conclusion."""
    task, required_paths, boundary = definition
    if not required_paths:
        return {
            "task": task,
            "status": "not_applicable",
            "required_inputs": [],
            "boundary": boundary,
        }
    modules_a = person_a.get("modules", {}) if isinstance(person_a.get("modules"), Mapping) else {}
    modules_b = person_b.get("modules", {}) if isinstance(person_b.get("modules"), Mapping) else {}
    inputs = []
    for path in required_paths:
        a_value = _get_path(modules_a, path)
        b_value = _get_path(modules_b, path)
        a_status, b_status = _status(a_value), _status(b_value)
        if a_status == b_status == "executed":
            status = "ready_for_comparison"
        elif "blocked" in {a_status, b_status}:
            status = "blocked"
        else:
            status = "parameter_sensitive"
        inputs.append({
            "source_path": f"modules.{path}",
            "status": status,
            "person_a_status": a_status,
            "person_b_status": b_status,
        })
    overall = "ready_for_comparison"
    if any(row["status"] == "blocked" for row in inputs):
        overall = "blocked"
    elif any(row["status"] == "parameter_sensitive" for row in inputs):
        overall = "parameter_sensitive"
    return {
        "task": task,
        "status": overall,
        "required_inputs": inputs,
        "boundary": boundary,
    }


def build_execution_receipt(person_a: Mapping[str, Any], person_b: Mapping[str, Any]) -> dict[str, Any]:
    """Return a non-identifying audit receipt for a pair of full readings."""
    a, b = _packet(person_a), _packet(person_b)
    profile_a, profile_b = _profile(a), _profile(b)
    profile_complete = all(profile_a.values()) and all(profile_b.values())
    profile_match = profile_complete and all(profile_a[key] == profile_b[key] for key in profile_a)
    rows = []
    for definition in REQUIRED_TECHNIQUES:
        a_row, b_row = _technique_row(a, definition), _technique_row(b, definition)
        combined = "executed" if a_row["status"] == b_row["status"] == "executed" else "blocked"
        if combined == "blocked" and {a_row["status"], b_row["status"]} <= {"executed", "partial", "parameter_sensitive", "observation_only", "guarded"}:
            combined = "parameter_sensitive"
        rows.append({
            "technique": definition[0],
            "status": combined,
            "person_a": a_row,
            "person_b": b_row,
        })
    return {
        "schema": SCHEMA,
        "calculation_profile": {"person_a": profile_a, "person_b": profile_b, "compatible": profile_match},
        "profile_gate": "passed" if profile_match else "blocked",
        "profile_gate_reason": None if profile_match else (
            "calculation_profile_incomplete" if not profile_complete else "calculation_profile_mismatch"
        ),
        "individual_technique_audit": rows,
        "pair_execution_tasks": [_pair_task_row(a, b, task) for task in PAIR_TASKS],
        "boundary": (
            "This receipt proves packet presence and calculation-profile comparability only. "
            "It does not turn a module into a conclusion; pair tasks, book evidence, MEVG and case calibration remain required."
        ),
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="Validate two full-reading packets before a full synastry interpretation.")
    parser.add_argument("--person-a", required=True, help="JSON full-reading or export packet for person A")
    parser.add_argument("--person-b", required=True, help="JSON full-reading or export packet for person B")
    parser.add_argument("--output", help="Optional receipt path; do not place customer data in a repository path.")
    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)
    receipt = build_execution_receipt(person_a, person_b)
    encoded = json.dumps(receipt, 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())
