#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Western astrology evidence packet contract."""

from __future__ import annotations

from typing import Any

try:
    from western_kp_support import summarize_kp_support
except ImportError:  # pragma: no cover - package import path
    from scripts.western_kp_support import summarize_kp_support


REQUIRED_SECTIONS = [
    "natal",
    "timing_techniques",
    "signals",
]

DEFAULT_KP_SUPPORT_BOUNDARY = (
    "KP support scaffolding only; Western evidence cannot promote KP timing or cusp truth by itself."
)


def _section(value: Any, source_path: str) -> dict[str, Any]:
    present = bool(value)
    return {
        "status": "used" if present else "missing",
        "source_path": source_path,
    }


def _normalize_signals(signals: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
    normalized: list[dict[str, Any]] = []
    for item in signals or []:
        if not isinstance(item, dict) or not item.get("theme") or not item.get("claim"):
            continue
        normalized.append(
            {
                "theme": str(item.get("theme")),
                "claim": str(item.get("claim")),
                "timing": str(item.get("timing") or "unspecified"),
                "source": str(item.get("source") or "western_evidence_packet"),
            }
        )
    return normalized


def _coerce_layer_payload(layer: Any) -> Any:
    if isinstance(layer, dict) and "raw_result" in layer:
        return layer.get("raw_result")
    return layer


def _layer_executed(layer: Any) -> bool:
    if not isinstance(layer, dict):
        return bool(layer)
    status = str(layer.get("status") or "")
    return status in {"executed", "used", "complete", "partial"} or bool(layer.get("raw_result"))


def _extract_western_natal(unified_western_reading: dict[str, Any]) -> dict[str, Any]:
    layers = unified_western_reading.get("layers") if isinstance(unified_western_reading.get("layers"), dict) else {}
    natal_layer = layers.get("natal") if isinstance(layers.get("natal"), dict) else {}
    natal_payload = _coerce_layer_payload(natal_layer)
    return natal_payload if isinstance(natal_payload, dict) else {}


def _extract_western_timing(unified_western_reading: dict[str, Any]) -> dict[str, Any]:
    layers = unified_western_reading.get("layers") if isinstance(unified_western_reading.get("layers"), dict) else {}
    timing: dict[str, Any] = {}
    for layer_name, layer in layers.items():
        if layer_name == "natal":
            continue
        if not isinstance(layer, dict):
            continue
        if _layer_executed(layer):
            timing[layer_name] = _coerce_layer_payload(layer)
        else:
            timing[layer_name] = {"status": str(layer.get("status") or "blocked"), "reason": layer.get("reason")}
    return timing


def _count_timing_layers(timing_techniques: dict[str, Any]) -> tuple[list[str], list[str]]:
    executed: list[str] = []
    blocked: list[str] = []
    for name, value in timing_techniques.items():
        if isinstance(value, dict) and str(value.get("status") or "used") == "blocked":
            blocked.append(name)
        else:
            executed.append(name)
    return sorted(executed), sorted(blocked)


def build_support_signal(
    *,
    theme: str,
    claim: str,
    timing: str = "unspecified",
    source: str = "western_auxiliary_manual_signal",
) -> dict[str, Any]:
    return {
        "theme": str(theme),
        "claim": str(claim),
        "timing": str(timing or "unspecified"),
        "source": str(source or "western_auxiliary_manual_signal"),
    }


def _normalize_kp_support(kp_support: dict[str, Any] | None) -> dict[str, Any]:
    payload = kp_support if isinstance(kp_support, dict) else {}
    raw_convergence = payload.get("convergence_inputs") or []
    if isinstance(raw_convergence, dict):
        convergence_inputs: list[dict[str, Any]] | dict[str, Any] = dict(raw_convergence)
    else:
        convergence_inputs = []
        for item in raw_convergence:
            if not isinstance(item, dict) or not item.get("technique") or not item.get("signal"):
                continue
            convergence_inputs.append(
                {
                    "technique": str(item.get("technique")),
                    "signal": str(item.get("signal")),
                    "orb": str(item.get("orb") or "unspecified"),
                }
            )

    raw_negative = payload.get("negative_evidence") or []
    if isinstance(raw_negative, dict):
        negative_evidence: list[dict[str, Any]] | dict[str, Any] = dict(raw_negative)
    else:
        negative_evidence = []
        for item in raw_negative:
            if not isinstance(item, dict) or not item.get("type") or not item.get("detail"):
                continue
            negative_evidence.append(
                {
                    "type": str(item.get("type")),
                    "detail": str(item.get("detail")),
                }
            )

    return {
        "status": str(payload.get("status") or "not_requested"),
        "convergence_inputs": convergence_inputs,
        "negative_evidence": negative_evidence,
        "claim_boundary": str(payload.get("claim_boundary") or DEFAULT_KP_SUPPORT_BOUNDARY),
    }


def _normalize_real_case_support(real_case_support: dict[str, Any] | None) -> dict[str, Any]:
    payload = real_case_support if isinstance(real_case_support, dict) else {}
    matched_cases: list[dict[str, Any]] = []
    for item in payload.get("matched_cases") or []:
        if not isinstance(item, dict) or not item.get("case_id"):
            continue
        matched_cases.append(
            {
                "case_id": str(item.get("case_id")),
                "event_type": str(item.get("event_type") or "unknown_event"),
                "event_date": str(item.get("event_date") or "unknown_date"),
                "subject": str(item.get("subject") or "unknown_subject"),
                "birth_time_rating": str(item.get("birth_time_rating") or "unknown"),
                "source_grade": str(item.get("source_grade") or "unknown"),
            }
        )
    calibration = payload.get("calibration") if isinstance(payload.get("calibration"), dict) else {}
    return {
        "status": str(payload.get("status") or "not_requested"),
        "primary_theme": str(payload.get("primary_theme") or "general"),
        "matched_case_count": int(payload.get("matched_case_count") or len(matched_cases)),
        "matched_cases": matched_cases,
        "manifest_case_count": int(payload.get("manifest_case_count") or 0),
        "calibration": calibration,
        "claim_boundary": str(
            payload.get("claim_boundary")
            or "Western real-case support is audit-only until replay specificity and holdout closure are independently verified."
        ),
    }


def build_western_evidence_packet(
    *,
    route_packet: dict[str, Any],
    natal: dict[str, Any] | None,
    timing_techniques: dict[str, Any] | None,
    signals: list[dict[str, Any]] | None,
    kp_support: dict[str, Any] | None = None,
    real_case_support: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Materialize a small auditable Western evidence packet."""

    normalized_signals = _normalize_signals(signals)
    normalized_kp_support = _normalize_kp_support(kp_support)
    normalized_real_case_support = _normalize_real_case_support(real_case_support)
    sections = {
        "natal": _section(natal, "western.natal"),
        "timing_techniques": _section(timing_techniques, "western.timing_techniques"),
        "signals": _section(normalized_signals, "western.signals"),
    }
    missing = [name for name in REQUIRED_SECTIONS if sections[name]["status"] == "missing"]
    return {
        "system": "western_astrology",
        "status": "complete" if not missing else "partial",
        "route": dict(route_packet),
        "required_sections": list(REQUIRED_SECTIONS),
        "sections": sections,
        "natal": natal or {},
        "timing_techniques": timing_techniques or {},
        "signals": normalized_signals,
        "kp_support": normalized_kp_support,
        "real_case_support": normalized_real_case_support,
        "missing_sections": missing,
        "license_boundary": (
            "This packet stores derived evidence only. Kerykeion, pyswisseph, Flatlib, Immanuel, or desktop "
            "software outputs must remain external oracle inputs unless their licenses permit bundling."
        ),
    }


def build_western_auxiliary_evidence_packet(
    *,
    route_packet: dict[str, Any],
    unified_western_reading: dict[str, Any] | None = None,
    signals: list[dict[str, Any]] | None = None,
    real_case_support: dict[str, Any] | None = None,
    kp_support: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Convert the unified Western reading into a support-only evidence packet.

    This is the safe integration boundary used by Jyotish orchestration: it
    carries tropical/classical evidence as corroboration, conflict, and negative
    evidence only. It never promotes Western calculations into primary Jyotish
    timing truth.
    """

    reading = unified_western_reading if isinstance(unified_western_reading, dict) else {}
    natal = _extract_western_natal(reading)
    timing_techniques = _extract_western_timing(reading)
    normalized_signals = _normalize_signals(signals)
    support_payload = kp_support if isinstance(kp_support, dict) else summarize_kp_support(
        route_packet=route_packet,
        natal=natal,
        timing_techniques=timing_techniques,
        signals=normalized_signals,
    )
    packet = build_western_evidence_packet(
        route_packet=route_packet,
        natal=natal,
        timing_techniques=timing_techniques,
        signals=normalized_signals,
        kp_support=support_payload,
        real_case_support=real_case_support,
    )
    executed_layers, blocked_layers = _count_timing_layers(timing_techniques)
    packet["support_mode"] = "auxiliary_only"
    packet["source_reading_status"] = str(reading.get("status") or "missing")
    packet["modern_western_layers"] = {
        "status": "used" if executed_layers else "missing",
        "executed_layers": executed_layers,
        "blocked_layers": blocked_layers,
    }
    packet["classical_western_layers"] = {
        "status": "used" if "classical" in executed_layers or "profection" in executed_layers else "partial",
        "executed_layers": [name for name in executed_layers if name in {"classical", "profection", "zodiacal_release"}],
        "guarded_layers": [name for name in blocked_layers if name in {"zodiacal_release", "classical_usable_loop"}],
        "claim_boundary": "Classical layers may explain annual themes and dignity/sect context; horary, electional, and ZR final prediction remain guarded unless case gates close.",
    }
    packet["authority_boundary"] = {
        "primary_engine": "jyotish",
        "western_role": "support_conflict_negative_evidence_only",
        "can_raise_confidence": True,
        "can_override_jyotish": False,
        "can_promote_timing_precision": False,
    }
    return packet



def build_western_kp_combined_packet(
    *,
    route_packet: dict[str, Any],
    natal: dict[str, Any] | None,
    timing_techniques: dict[str, Any] | None,
    signals: list[dict[str, Any]] | None,
    kp_probe: dict[str, Any] | None = None,
    kp_support: dict[str, Any] | None = None,
    real_case_support: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Build a western packet with an explicit KP bridge layer."""

    packet = build_western_evidence_packet(
        route_packet=route_packet,
        natal=natal,
        timing_techniques=timing_techniques,
        signals=signals,
        kp_support=kp_support,
        real_case_support=real_case_support,
    )
    kp_probe_payload = kp_probe if isinstance(kp_probe, dict) else {}
    packet["kp_bridge"] = {
        "status": str(kp_probe_payload.get("claim_status") or kp_probe_payload.get("status") or "blocked"),
        "probe_scope": str(kp_probe_payload.get("scope") or "kp_probe"),
        "ruling_planets": kp_probe_payload.get("ruling_planets") or {},
        "kp_lords_by_planet": kp_probe_payload.get("kp_lords_by_planet") or {},
        "planet_significators": kp_probe_payload.get("planet_significators") or {},
        "house_significators": kp_probe_payload.get("house_significators") or {},
        "cusp_contract": kp_probe_payload.get("kp_cusp_contract") or {},
        "claim_boundary": str(
            kp_probe_payload.get("claim_boundary")
            or "KP may validate or contradict western timing signals, but it remains a support layer until exact cusp closure is available."
        ),
    }
    packet["sections"]["kp_bridge"] = {
        "status": "used" if kp_probe_payload else "missing",
        "source_path": "western.kp_bridge",
    }
    return packet
