#!/usr/bin/env python3
"""Summarize source-save load-only evidence against source-exit runtime proof attempts."""
from __future__ import annotations

import argparse
import html
import json
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "out"
LOAD_VARIANT_POLL = OUT / "runtime_selected_pointer_source_savedata_load_variants_poll.json"
LOAD_COORDINATE_POLL = OUT / "runtime_selected_pointer_source_savedata_load_coordinate_poll.json"
LOAD_CONFIRMED_EXIT_POLL = OUT / "runtime_selected_pointer_source_exit_branch_state_load_confirmed_poll.json"
ADAPTIVE_EXIT_POLL = OUT / "runtime_selected_pointer_source_exit_adaptive_coordinate_poll.json"
ADAPTIVE_TRAIL_START_POLL = OUT / "runtime_selected_pointer_source_exit_adaptive_trail_start_poll.json"
MAPSET_ALIASES = OUT / "save_selector_mapset_aliases.json"
SCENE_ADJACENCY_INDEX = OUT / "save_selector_scene_adjacency_index.json"
GLOBAL_SELECTED_POINTER_PATHS = OUT / "save_selector_global_selected_pointer_paths.json"
SOURCE_MAP = "map1_01a"
TARGET_MAP = "map2_02d"
SOURCE_SELECTOR = "0:0"
TARGET_SELECTOR = "2:0"
FAILED_RUNTIME_SOURCE_SAVE_LOAD_VARIANT_GATE_IDS = [
    "strict-source-hotspot",
    "selected-root-execution",
    "route-selector-current-root-observation",
    "source-exit-candidate-observation",
    "route-promotion-evidence",
]
RUNTIME_SOURCE_SAVE_LOAD_VARIANT_MISSING_EVIDENCE = [
    "strict map1_01a source hotspot or equivalent runtime trigger",
    "selected-root/current-root execution while the source-save path runs",
    "runtime source-ready path reaching selector 2:0/current root instead of selector 48:13",
    "candidate/outside exit coordinate or actor/trail observation for map1_01a -> map2_02d",
    "route-promotion evidence linking the source save to map2_02d",
]
RUNTIME_SOURCE_SAVE_LOAD_VARIANT_EVIDENCE_REFS = [
    {
        "path": "out/runtime_selected_pointer_source_savedata_load_variants_poll.json",
        "fields": ["observedSelectors", "observedPublicSaveSelectors", "sampleCount"],
    },
    {
        "path": "out/runtime_selected_pointer_source_savedata_load_coordinate_poll.json",
        "fields": ["observedSelectors", "sourceStartTileObserved", "sampleCount"],
    },
    {
        "path": "out/runtime_selected_pointer_source_exit_branch_state_load_confirmed_poll.json",
        "fields": ["observedSelectors", "sourceExitAnalysis", "sampleCount"],
    },
    {
        "path": "out/runtime_selected_pointer_source_exit_adaptive_coordinate_poll.json",
        "fields": ["classification", "sourceReadyCount", "candidateObserved", "outsideObserved", "sampleCount"],
    },
    {
        "path": "out/runtime_selected_pointer_source_exit_adaptive_trail_start_poll.json",
        "fields": ["classification", "sourceReadyCount", "candidateObserved", "outsideObserved", "sampleCount"],
    },
    {
        "path": "out/save_selector_mapset_aliases.json",
        "fields": ["aliasGroups", "selectors"],
    },
    {
        "path": "out/save_selector_scene_adjacency_index.json",
        "fields": ["rows", "selectorAdjacencyOnlyPairCount", "strictEventBackedCount"],
    },
    {
        "path": "out/save_selector_global_selected_pointer_paths.json",
        "fields": ["selectedPointerGlobalHex", "opcode07Count", "opcode08Count", "opcode09Count"],
    },
]


def existing_evidence_refs() -> list[dict[str, Any]]:
    return [
        ref
        for ref in RUNTIME_SOURCE_SAVE_LOAD_VARIANT_EVIDENCE_REFS
        if (ROOT / ref["path"]).exists()
    ]


def list_text(values: list[Any] | None) -> str:
    return ",".join(str(value) for value in values or []) or "-"


def compact_json(value: object) -> str:
    return json.dumps(value or {}, sort_keys=True, separators=(",", ":"))


def load_json(path: Path) -> dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}


def selector_count_rows(row: dict[str, Any]) -> list[dict[str, Any]]:
    rows = []
    for item in row.get("uniqueSelectorContexts") or []:
        if not isinstance(item, dict):
            continue
        rows.append({
            "selector": item.get("selector"),
            "count": item.get("count"),
            "rootHex": item.get("rootHex"),
            "fieldMaps": item.get("fieldMaps") or [],
        })
    return rows


def field_maps_for_selector(row: dict[str, Any], selector: str | None) -> list[str]:
    if not selector:
        return []
    maps: set[str] = set()
    for item in selector_count_rows(row):
        if item.get("selector") == selector:
            maps.update(str(value) for value in item.get("fieldMaps") or [])
    for event in row.get("events") or []:
        context = event.get("selectorContext") or {}
        if context.get("selector") == selector:
            maps.update(str(value) for value in context.get("fieldMaps") or [])
    return sorted(maps)


def selector_event_path(row: dict[str, Any], fallback_selectors: list[str]) -> list[str]:
    path: list[str] = []
    for event in row.get("events") or []:
        context = event.get("selectorContext") or {}
        selector = context.get("selector")
        if selector and (not path or path[-1] != selector):
            path.append(str(selector))
    if path:
        return path
    return [str(selector) for selector in fallback_selectors]


def first_non_source_selector(selectors: list[str]) -> str | None:
    for selector in selectors:
        if selector != SOURCE_SELECTOR:
            return selector
    return None


def camera_extent(camera_pairs: list[dict[str, Any]]) -> dict[str, Any]:
    xs = [
        int(pair.get("x"))
        for pair in camera_pairs
        if isinstance(pair.get("x"), int)
    ]
    ys = [
        int(pair.get("y"))
        for pair in camera_pairs
        if isinstance(pair.get("y"), int)
    ]
    total_count = sum(
        int(pair.get("count") or 0)
        for pair in camera_pairs
        if isinstance(pair.get("count"), int)
    )
    return {
        "minX": min(xs) if xs else None,
        "maxX": max(xs) if xs else None,
        "minY": min(ys) if ys else None,
        "maxY": max(ys) if ys else None,
        "sampleCount": total_count,
    }


def summarize_adaptive_row(row: dict[str, Any]) -> dict[str, Any]:
    selectors = [
        item.get("selector") if isinstance(item, dict) else str(item)
        for item in row.get("uniqueSelectorContexts") or []
    ]
    selector_path = selector_event_path(row, selectors)
    non_source = first_non_source_selector(selector_path)
    camera_pairs = row.get("cameraPairs") or []
    return {
        "name": row.get("name"),
        "candidateName": row.get("candidateName"),
        "attempt": row.get("attempt"),
        "sourceReady": row.get("sourceReady"),
        "pathExecuted": row.get("pathExecuted"),
        "sampleCount": row.get("sampleCount"),
        "pathStepCount": row.get("pathStepCount"),
        "selectors": selectors,
        "selectorCounts": selector_count_rows(row),
        "selectorPath": selector_path,
        "firstNonSourceSelector": non_source,
        "firstNonSourceFieldMaps": field_maps_for_selector(row, non_source),
        "cameraPairs": camera_pairs,
        "cameraExtent": camera_extent(camera_pairs),
        "cameraCandidateObserved": row.get("cameraCandidateObserved"),
        "cameraOutsideObserved": row.get("cameraOutsideObserved"),
        "actorCandidateSlots": row.get("actorCandidateSlots") or [],
        "trailCandidateSlots": row.get("trailCandidateSlots") or [],
        "actorOutsideSlots": row.get("actorOutsideSlots") or [],
        "trailOutsideSlots": row.get("trailOutsideSlots") or [],
        "routeSelectorHitCount": row.get("routeSelectorHitCount"),
        "currentRootHitCount": row.get("currentRootHitCount"),
        "branchStateAllZero": row.get("branchStateAllZero"),
    }


def summarize_ready_paths(
    adaptive_rows: list[dict[str, Any]],
    adaptive_trail_rows: list[dict[str, Any]],
) -> dict[str, Any]:
    ready_rows: list[dict[str, Any]] = []
    for family, rows in [("adaptiveExit", adaptive_rows), ("adaptiveTrailStart", adaptive_trail_rows)]:
        for row in rows:
            if row.get("sourceReady") and row.get("pathExecuted"):
                tagged = dict(row)
                tagged["family"] = family
                ready_rows.append(tagged)
    first_non_source_counts: dict[str, int] = {}
    first_non_source_field_maps: dict[str, set[str]] = {}
    camera_pairs: list[dict[str, Any]] = []
    route_or_current_count = 0
    candidate_or_outside_count = 0
    for row in ready_rows:
        selector = row.get("firstNonSourceSelector")
        if selector:
            first_non_source_counts[selector] = first_non_source_counts.get(selector, 0) + 1
            first_non_source_field_maps.setdefault(selector, set()).update(
                str(value) for value in row.get("firstNonSourceFieldMaps") or []
            )
        camera_pairs.extend(row.get("cameraPairs") or [])
        if row.get("routeSelectorHitCount") or row.get("currentRootHitCount"):
            route_or_current_count += 1
        if (
            row.get("cameraCandidateObserved")
            or row.get("cameraOutsideObserved")
            or row.get("actorCandidateSlots")
            or row.get("trailCandidateSlots")
            or row.get("actorOutsideSlots")
            or row.get("trailOutsideSlots")
        ):
            candidate_or_outside_count += 1
    dominant_selector = None
    if first_non_source_counts:
        dominant_selector = sorted(
            first_non_source_counts,
            key=lambda selector: (-first_non_source_counts[selector], selector),
        )[0]
    all_divert = bool(
        ready_rows
        and route_or_current_count == 0
        and candidate_or_outside_count == 0
        and all(row.get("firstNonSourceSelector") for row in ready_rows)
    )
    return {
        "sourceSelector": SOURCE_SELECTOR,
        "targetSelector": "2:0",
        "readyPathCount": len(ready_rows),
        "adaptiveReadyPathCount": sum(1 for row in ready_rows if row.get("family") == "adaptiveExit"),
        "adaptiveTrailReadyPathCount": sum(1 for row in ready_rows if row.get("family") == "adaptiveTrailStart"),
        "readyPathNames": [row.get("name") for row in ready_rows],
        "firstNonSourceSelectorCounts": first_non_source_counts,
        "dominantNonRouteSelector": dominant_selector,
        "dominantNonRouteFieldMaps": sorted(first_non_source_field_maps.get(dominant_selector, set()))
        if dominant_selector
        else [],
        "routeOrCurrentReadyPathCount": route_or_current_count,
        "candidateOrOutsideReadyPathCount": candidate_or_outside_count,
        "allReadyPathsDivertToNonRouteSelector": all_divert,
        "diversionClassification": "source-ready-path-diverts-to-48:13-before-exit-candidates"
        if all_divert and dominant_selector == "48:13"
        else "source-ready-path-diversion-unclassified",
        "cameraExtent": camera_extent(camera_pairs),
        "rows": [
            {
                "family": row.get("family"),
                "name": row.get("name"),
                "candidateName": row.get("candidateName"),
                "selectorPath": row.get("selectorPath"),
                "firstNonSourceSelector": row.get("firstNonSourceSelector"),
                "firstNonSourceFieldMaps": row.get("firstNonSourceFieldMaps"),
                "cameraExtent": row.get("cameraExtent"),
                "routeSelectorHitCount": row.get("routeSelectorHitCount"),
                "currentRootHitCount": row.get("currentRootHitCount"),
                "candidateOrOutsideObserved": bool(
                    row.get("cameraCandidateObserved")
                    or row.get("cameraOutsideObserved")
                    or row.get("actorCandidateSlots")
                    or row.get("trailCandidateSlots")
                    or row.get("actorOutsideSlots")
                    or row.get("trailOutsideSlots")
                ),
            }
            for row in ready_rows
        ],
    }


def selector_matches(values: list[Any] | None, selector: str | None) -> bool:
    if not selector:
        return False
    return any(str(value) == selector for value in values or [])


def find_alias_group(mapset_aliases: dict[str, Any], selector: str | None) -> dict[str, Any]:
    if not selector:
        return {}
    for group in mapset_aliases.get("duplicateGroups") or []:
        aliases = group.get("aliases") or []
        if any(alias.get("selector") == selector for alias in aliases if isinstance(alias, dict)):
            return group
    target_group = mapset_aliases.get("targetAliasGroup") or {}
    aliases = target_group.get("aliases") or []
    if any(alias.get("selector") == selector for alias in aliases if isinstance(alias, dict)):
        return target_group
    return {}


def alias_row(alias_group: dict[str, Any], selector: str | None) -> dict[str, Any]:
    for alias in alias_group.get("aliases") or []:
        if isinstance(alias, dict) and alias.get("selector") == selector:
            return alias
    return {}


def scene_adjacency_rows(scene_adjacency: dict[str, Any], selector: str | None) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    for row in scene_adjacency.get("pairRows") or []:
        if selector_matches(row.get("selectors"), selector):
            rows.append({
                "source": row.get("source"),
                "target": row.get("target"),
                "occurrenceCount": row.get("occurrenceCount"),
                "selectors": row.get("selectors") or [],
                "leafPointers": row.get("leafPointers") or [],
                "sourceRecords": row.get("sourceRecords") or [],
                "targetRecords": row.get("targetRecords") or [],
                "strictEventBacked": bool(row.get("strictEventBacked")),
                "confirmedReviewBacked": bool(row.get("confirmedReviewBacked")),
                "selectorAdjacencyOnly": bool(row.get("selectorAdjacencyOnly")),
                "classification": row.get("classification"),
            })
    return rows


def selected_pointer_path_for(
    selected_pointer_paths: dict[str, Any],
    selector: str | None,
) -> dict[str, Any]:
    if not selector:
        return {}
    for row in selected_pointer_paths.get("selectorRootScans") or []:
        if selector_matches(row.get("selectorLabels"), selector):
            return {
                "primarySelector": row.get("primarySelector"),
                "selectorLabels": row.get("selectorLabels") or [],
                "rootHex": row.get("rootHex"),
                "rangeHex": row.get("rangeHex"),
                "section": row.get("section"),
                "isCurrentRoot": bool(row.get("isCurrentRoot")),
                "fieldMaps": row.get("fieldMaps") or [],
                "fieldMapCount": row.get("fieldMapCount"),
                "opcode07Count": row.get("opcode07Count"),
                "opcode08Count": row.get("opcode08Count"),
                "opcode09Count": row.get("opcode09Count"),
                "opcode07SelectsCurrentRootCount": row.get("opcode07SelectsCurrentRootCount"),
                "opcode07SelectsCurrentRangeCount": row.get("opcode07SelectsCurrentRangeCount"),
                "opcode09StoresCurrentRootCount": row.get("opcode09StoresCurrentRootCount"),
                "opcode09StoresCurrentRangeCount": row.get("opcode09StoresCurrentRangeCount"),
                "opcode08NearestCurrentRootProducerCount": row.get(
                    "opcode08NearestCurrentRootProducerCount"
                ),
                "opcode08NearestCurrentRangeProducerCount": row.get(
                    "opcode08NearestCurrentRangeProducerCount"
                ),
                "promotingCandidateCount": row.get("promotingCandidateCount"),
            }
    return {}


def diversion_selector_context(
    ready_path_summary: dict[str, Any],
    mapset_aliases: dict[str, Any],
    scene_adjacency: dict[str, Any],
    selected_pointer_paths: dict[str, Any],
) -> dict[str, Any]:
    selector = ready_path_summary.get("dominantNonRouteSelector")
    field_maps = ready_path_summary.get("dominantNonRouteFieldMaps") or []
    alias_group = find_alias_group(mapset_aliases, selector)
    alias = alias_row(alias_group, selector)
    aliases = [
        row.get("selector")
        for row in alias_group.get("aliases") or []
        if isinstance(row, dict) and row.get("selector")
    ]
    adjacency_rows = scene_adjacency_rows(scene_adjacency, selector)
    selected_path = selected_pointer_path_for(selected_pointer_paths, selector)
    strict_count = sum(1 for row in adjacency_rows if row.get("strictEventBacked"))
    confirmed_count = sum(1 for row in adjacency_rows if row.get("confirmedReviewBacked"))
    selector_only_count = sum(1 for row in adjacency_rows if row.get("selectorAdjacencyOnly"))
    contains_source = bool(alias_group.get("containsSource")) or SOURCE_MAP in field_maps
    contains_target = bool(alias_group.get("containsTarget")) or TARGET_MAP in field_maps
    selected_path_current_count = sum(
        int(selected_path.get(key) or 0)
        for key in [
            "opcode07SelectsCurrentRootCount",
            "opcode07SelectsCurrentRangeCount",
            "opcode09StoresCurrentRootCount",
            "opcode09StoresCurrentRangeCount",
            "opcode08NearestCurrentRootProducerCount",
            "opcode08NearestCurrentRangeProducerCount",
            "promotingCandidateCount",
        ]
    )
    route_promotion_found = bool(
        selector == TARGET_SELECTOR
        or contains_source and contains_target
        or strict_count
        or confirmed_count
        or selected_path_current_count
        or selected_pointer_paths.get("selectedRootExecutionRefFound")
    )
    if (
        selector
        and not route_promotion_found
        and selector_only_count == len(adjacency_rows)
        and not contains_source
        and not contains_target
    ):
        classification = "non-route-selector-adjacency-only"
    else:
        classification = "diversion-selector-context-unclassified"
    return {
        "sourceSelector": SOURCE_SELECTOR,
        "targetSelector": TARGET_SELECTOR,
        "selector": selector,
        "fieldMaps": field_maps,
        "classification": classification,
        "selectorEqualsTargetSelector": selector == TARGET_SELECTOR,
        "selectorInRoutePair": selector in {SOURCE_SELECTOR, TARGET_SELECTOR},
        "containsSourceMap": contains_source,
        "containsTargetMap": contains_target,
        "aliasGroupSelectors": aliases,
        "aliasGroupFieldMaps": alias_group.get("fieldMaps") or field_maps,
        "aliasRootHex": alias.get("rootHex"),
        "aliasRootAddressOrderIndex": alias.get("rootAddressOrderIndex"),
        "aliasSelectedPointerEntryHex": alias.get("selectedPointerEntryHex"),
        "aliasFillCount": alias.get("fillCount"),
        "aliasContainsSource": bool(alias_group.get("containsSource")),
        "aliasContainsTarget": bool(alias_group.get("containsTarget")),
        "sceneAdjacencyRows": adjacency_rows,
        "sceneAdjacencyRowCount": len(adjacency_rows),
        "sceneAdjacencySelectorOnlyPairCount": selector_only_count,
        "sceneAdjacencyStrictEventBackedCount": strict_count,
        "sceneAdjacencyConfirmedReviewBackedCount": confirmed_count,
        "selectedPointerPath": selected_path,
        "selectedPointerPathFound": bool(selected_path),
        "selectedPointerPathSelectsOrStoresCurrentCount": selected_path_current_count,
        "selectedRootExecutionRefFound": bool(selected_pointer_paths.get("selectedRootExecutionRefFound")),
        "routePromotionEvidenceFound": route_promotion_found,
        "conclusion": (
            "Source-ready paths leave public selector 0:0 through selector 48:13, which belongs to the "
            "map2_04l/map2_05e scene-list alias group. That selector has selector-adjacency-only rows and "
            "no map1_01a/map2_02d route-pair, strict event, confirmed review, current-root, or selected-root "
            "promotion evidence."
        )
        if classification == "non-route-selector-adjacency-only"
        else "The diversion selector context did not match the known non-route-only pattern.",
    }


def selector_rows(summary: dict[str, Any]) -> list[dict[str, Any]]:
    rows = []
    for row in summary.get("rows") or []:
        selectors = [
            item.get("selector") if isinstance(item, dict) else str(item)
            for item in row.get("uniqueSelectorContexts") or []
        ]
        rows.append({
            "name": row.get("name"),
            "sampleCount": row.get("sampleCount"),
            "selectors": selectors,
            "sourceSelectorObserved": SOURCE_SELECTOR in selectors,
            "routeSelectorHitCount": row.get("routeSelectorHitCount"),
            "currentRootHitCount": row.get("currentRootHitCount"),
        })
    return rows


def exit_candidate_rows(summary: dict[str, Any]) -> list[dict[str, Any]]:
    return [
        {
            "name": row.get("name"),
            "sampleCount": row.get("sampleCount"),
            "selectors": [
                item.get("selector") if isinstance(item, dict) else str(item)
                for item in row.get("selectors") or []
            ],
            "candidateTile": row.get("candidateTile"),
            "outsideTile": row.get("outsideTile"),
            "candidateSide": row.get("candidateSide"),
            "cameraCandidateObserved": row.get("cameraCandidateObserved"),
            "cameraOutsideObserved": row.get("cameraOutsideObserved"),
            "actorCandidateSlots": row.get("actorCandidateSlots") or [],
            "trailCandidateSlots": row.get("trailCandidateSlots") or [],
            "actorOutsideSlots": row.get("actorOutsideSlots") or [],
            "trailOutsideSlots": row.get("trailOutsideSlots") or [],
            "routeSelectorHitCount": row.get("routeSelectorHitCount"),
            "currentRootHitCount": row.get("currentRootHitCount"),
            "branchStateAllZero": row.get("branchStateAllZero"),
        }
        for row in (summary.get("sourceExitAnalysis") or {}).get("rows") or []
    ]


def build_summary(
    load_variant_poll: dict[str, Any] | None = None,
    load_coordinate_poll: dict[str, Any] | None = None,
    load_confirmed_exit_poll: dict[str, Any] | None = None,
    adaptive_exit_poll: dict[str, Any] | None = None,
    adaptive_trail_start_poll: dict[str, Any] | None = None,
    mapset_aliases: dict[str, Any] | None = None,
    scene_adjacency: dict[str, Any] | None = None,
    selected_pointer_paths: dict[str, Any] | None = None,
) -> dict[str, Any]:
    load_variant_poll = load_variant_poll or {}
    load_coordinate_poll = load_coordinate_poll or {}
    load_confirmed_exit_poll = load_confirmed_exit_poll or {}
    adaptive_exit_poll = adaptive_exit_poll or {}
    adaptive_trail_start_poll = adaptive_trail_start_poll or {}
    mapset_aliases = mapset_aliases or {}
    scene_adjacency = scene_adjacency or {}
    selected_pointer_paths = selected_pointer_paths or {}
    load_variant_rows = selector_rows(load_variant_poll)
    coordinate_analysis = load_coordinate_poll.get("sourceLoadCoordinateAnalysis") or {}
    exit_rows = exit_candidate_rows(load_confirmed_exit_poll)
    load_variant_observed = SOURCE_SELECTOR in (load_variant_poll.get("observedPublicSaveSelectors") or [])
    coordinate_source_observed = bool(coordinate_analysis.get("sourceSelectorObserved"))
    coordinate_start_observed = bool(coordinate_analysis.get("sourceStartTileObserved"))
    exit_observed = SOURCE_SELECTOR in (load_confirmed_exit_poll.get("observedPublicSaveSelectors") or [])
    route_hit = bool(load_confirmed_exit_poll.get("anyReachedRouteSelectorContext"))
    current_hit = bool(load_confirmed_exit_poll.get("anyReachedCurrentRoot"))
    adaptive_route_hit = bool(adaptive_exit_poll.get("anyReachedRouteSelectorContext"))
    adaptive_current_hit = bool(adaptive_exit_poll.get("anyReachedCurrentRoot"))
    adaptive_trail_route_hit = bool(adaptive_trail_start_poll.get("anyReachedRouteSelectorContext"))
    adaptive_trail_current_hit = bool(adaptive_trail_start_poll.get("anyReachedCurrentRoot"))
    adaptive_source_ready = bool(adaptive_exit_poll.get("sourceReadyCount") or adaptive_trail_start_poll.get("sourceReadyCount"))
    adaptive_candidate = bool(adaptive_exit_poll.get("candidateObserved") or adaptive_trail_start_poll.get("candidateObserved"))
    adaptive_outside = bool(adaptive_exit_poll.get("outsideObserved") or adaptive_trail_start_poll.get("outsideObserved"))
    adaptive_rows = [summarize_adaptive_row(row) for row in adaptive_exit_poll.get("rows") or []]
    adaptive_trail_rows = [summarize_adaptive_row(row) for row in adaptive_trail_start_poll.get("rows") or []]
    ready_path_summary = summarize_ready_paths(adaptive_rows, adaptive_trail_rows)
    diversion_context = diversion_selector_context(
        ready_path_summary,
        mapset_aliases,
        scene_adjacency,
        selected_pointer_paths,
    )
    if adaptive_route_hit or adaptive_current_hit or adaptive_trail_route_hit or adaptive_trail_current_hit:
        classification = "route-observed"
        conclusion = "The adaptive source exit poll observed the route selector/current root."
    elif adaptive_source_ready and not adaptive_candidate and not adaptive_outside:
        classification = "source-ready-adaptive-exit-no-route"
        conclusion = (
            "The source save can load selector 0:0 with camera tile 0,2. Adaptive exit probes caught source-ready "
            "attempts from both the camera-derived start and the observed trail0 start before executing routeAssist "
            "paths. Those source-ready paths still observed no routeAssist exit coordinate, selector 2:0, or current "
            "root. The source save is therefore useful as source-load/start-coordinate context, not as strict "
            "exit-hotspot or selected-root execution proof."
        )
    elif coordinate_source_observed and coordinate_start_observed and not exit_observed:
        classification = "source-start-coordinate-observed-exit-path-source-not-observed"
        conclusion = (
            "A bounded load-menu variant can observe public selector 0:0 together with the source camera tile 0,2. "
            "However, the coordinate/branch-state exit-path poll with the same source save remains in selector 50:0 "
            "and does not observe any routeAssist exit coordinate, selector 2:0, or the current root. The source save "
            "is therefore useful as source-load/start-coordinate context, not as strict exit-hotspot or selected-root "
            "execution proof."
        )
    elif load_variant_observed and not exit_observed:
        classification = "load-only-source-observed-exit-path-source-not-observed"
        conclusion = (
            "A bounded load-menu variant can observe public selector 0:0, but the coordinate/branch-state exit-path "
            "poll with the same source save remains in selector 50:0 and does not observe map1_01a coordinates, "
            "selector 2:0, or the current root. The source save is therefore useful as loadability context only, "
            "not as strict source-hotspot or selected-root execution proof."
        )
    elif exit_observed and (route_hit or current_hit):
        classification = "route-observed"
        conclusion = "The source exit poll observed the route selector/current root."
    elif exit_observed:
        classification = "source-observed-exit-nonroute"
        conclusion = (
            "The source exit poll observed public selector 0:0, but did not reach selector 2:0/current root or a "
            "strict source coordinate."
        )
    else:
        classification = "source-not-observed-in-exit-path"
        conclusion = (
            "The source exit poll did not observe public selector 0:0; no route evidence is available from this run."
        )
    proof_found = classification == "route-observed"
    evidence_refs = existing_evidence_refs()
    return {
        "sourceMap": SOURCE_MAP,
        "targetMap": TARGET_MAP,
        "sourceSaveSelector": SOURCE_SELECTOR,
        "classification": classification,
        "promotionStatus": "blocked" if classification != "route-observed" else "candidate",
        "proofFound": proof_found,
        "runtimeSourceSaveLoadVariantProofFound": proof_found,
        "failedRuntimeSourceSaveLoadVariantGateIds": (
            [] if proof_found else FAILED_RUNTIME_SOURCE_SAVE_LOAD_VARIANT_GATE_IDS
        ),
        "missingEvidence": (
            [] if proof_found else RUNTIME_SOURCE_SAVE_LOAD_VARIANT_MISSING_EVIDENCE
        ),
        "evidenceRefs": evidence_refs,
        "evidenceRefCount": len(evidence_refs),
        "loadVariant": {
            "source": "runtime_selected_pointer_source_savedata_load_variants_poll",
            "sampleCount": load_variant_poll.get("sampleCount"),
            "sequenceCount": load_variant_poll.get("sequenceCount"),
            "observedSelectors": load_variant_poll.get("observedSelectors") or [],
            "publicSaveSelectors": load_variant_poll.get("publicSaveSelectors") or [],
            "observedPublicSaveSelectors": load_variant_poll.get("observedPublicSaveSelectors") or [],
            "sourceSaveObserved": load_variant_observed,
            "anyReachedRouteSelectorContext": bool(load_variant_poll.get("anyReachedRouteSelectorContext")),
            "anyReachedCurrentRoot": bool(load_variant_poll.get("anyReachedCurrentRoot")),
            "rows": load_variant_rows,
        },
        "coordinateLoad": {
            "source": "runtime_selected_pointer_source_savedata_load_coordinate_poll",
            "sampleCount": load_coordinate_poll.get("sampleCount"),
            "sequenceCount": load_coordinate_poll.get("sequenceCount"),
            "observedSelectors": load_coordinate_poll.get("observedSelectors") or [],
            "publicSaveSelectors": load_coordinate_poll.get("publicSaveSelectors") or [],
            "observedPublicSaveSelectors": load_coordinate_poll.get("observedPublicSaveSelectors") or [],
            "analysisClassification": coordinate_analysis.get("classification"),
            "sourceSaveObserved": coordinate_source_observed,
            "sourceStartTileObserved": coordinate_start_observed,
            "anyReachedRouteSelectorContext": bool(load_coordinate_poll.get("anyReachedRouteSelectorContext")),
            "anyReachedCurrentRoot": bool(load_coordinate_poll.get("anyReachedCurrentRoot")),
            "rows": coordinate_analysis.get("rows") or [],
        },
        "exitPath": {
            "source": "runtime_selected_pointer_source_exit_branch_state_load_confirmed_poll",
            "loadPrefix": load_confirmed_exit_poll.get("loadPrefix") or [],
            "sampleCount": load_confirmed_exit_poll.get("sampleCount"),
            "sequenceCount": load_confirmed_exit_poll.get("sequenceCount"),
            "observedSelectors": load_confirmed_exit_poll.get("observedSelectors") or [],
            "publicSaveSelectors": load_confirmed_exit_poll.get("publicSaveSelectors") or [],
            "observedPublicSaveSelectors": load_confirmed_exit_poll.get("observedPublicSaveSelectors") or [],
            "sourceSaveObserved": exit_observed,
            "anyReachedRouteSelectorContext": route_hit,
            "anyReachedCurrentRoot": current_hit,
            "candidateObserved": bool((load_confirmed_exit_poll.get("sourceExitAnalysis") or {}).get("anyCandidateObserved")),
            "outsideObserved": bool((load_confirmed_exit_poll.get("sourceExitAnalysis") or {}).get("anyOutsideObserved")),
            "actorOrTrailCandidateObserved": bool(
                (load_confirmed_exit_poll.get("sourceExitAnalysis") or {}).get("anyActorOrTrailCandidateObserved")
            ),
            "actorOrTrailOutsideObserved": bool(
                (load_confirmed_exit_poll.get("sourceExitAnalysis") or {}).get("anyActorOrTrailOutsideObserved")
            ),
            "rows": selector_rows(load_confirmed_exit_poll),
            "candidateRows": exit_rows,
        },
        "adaptiveExit": {
            "source": "runtime_selected_pointer_source_exit_adaptive_coordinate_poll",
            "sampleCount": adaptive_exit_poll.get("sampleCount"),
            "sequenceCount": adaptive_exit_poll.get("sequenceCount"),
            "candidatePlanCount": adaptive_exit_poll.get("candidatePlanCount"),
            "classification": adaptive_exit_poll.get("classification"),
            "observedSelectors": adaptive_exit_poll.get("observedSelectors") or [],
            "sourceReadyCount": adaptive_exit_poll.get("sourceReadyCount"),
            "candidateObserved": bool(adaptive_exit_poll.get("candidateObserved")),
            "outsideObserved": bool(adaptive_exit_poll.get("outsideObserved")),
            "anyReachedRouteSelectorContext": adaptive_route_hit,
            "anyReachedCurrentRoot": adaptive_current_hit,
            "rows": adaptive_rows,
        },
        "adaptiveTrailStart": {
            "source": "runtime_selected_pointer_source_exit_adaptive_trail_start_poll",
            "sampleCount": adaptive_trail_start_poll.get("sampleCount"),
            "sequenceCount": adaptive_trail_start_poll.get("sequenceCount"),
            "candidatePlanCount": adaptive_trail_start_poll.get("candidatePlanCount"),
            "classification": adaptive_trail_start_poll.get("classification"),
            "sourceStartTile": adaptive_trail_start_poll.get("sourceStartTile") or {},
            "sourceStartOrigin": adaptive_trail_start_poll.get("sourceStartOrigin"),
            "sourceReadyWatchKey": adaptive_trail_start_poll.get("sourceReadyWatchKey"),
            "observedSelectors": adaptive_trail_start_poll.get("observedSelectors") or [],
            "sourceReadyCount": adaptive_trail_start_poll.get("sourceReadyCount"),
            "candidateObserved": bool(adaptive_trail_start_poll.get("candidateObserved")),
            "outsideObserved": bool(adaptive_trail_start_poll.get("outsideObserved")),
            "anyReachedRouteSelectorContext": adaptive_trail_route_hit,
            "anyReachedCurrentRoot": adaptive_trail_current_hit,
            "rows": adaptive_trail_rows,
        },
        "readyPathSummary": ready_path_summary,
        "diversionSelectorContext": diversion_context,
        "strictSourceHotspotProofFound": False,
        "selectedRootExecutionProofFound": (
            route_hit
            or current_hit
            or adaptive_route_hit
            or adaptive_current_hit
            or adaptive_trail_route_hit
            or adaptive_trail_current_hit
        ),
        "routePromotionEvidenceFound": classification == "route-observed",
        "conclusion": conclusion,
    }


def markdown(summary: dict[str, Any]) -> str:
    load = summary.get("loadVariant") or {}
    coordinate = summary.get("coordinateLoad") or {}
    exit_path = summary.get("exitPath") or {}
    adaptive = summary.get("adaptiveExit") or {}
    adaptive_trail = summary.get("adaptiveTrailStart") or {}
    ready_paths = summary.get("readyPathSummary") or {}
    diversion = summary.get("diversionSelectorContext") or {}
    selected_path = diversion.get("selectedPointerPath") or {}
    ready_extent = ready_paths.get("cameraExtent") or {}
    lines = [
        "# Runtime Source Save Load Variant Context",
        "",
        f"- route: `{summary.get('sourceMap')}` -> `{summary.get('targetMap')}`",
        f"- source selector: `{summary.get('sourceSaveSelector')}`",
        f"- classification: `{summary.get('classification')}`",
        f"- promotion status: `{summary.get('promotionStatus')}`",
        f"- proof found: {summary.get('proofFound')}",
        f"- runtime source-save load variant proof found: {summary.get('runtimeSourceSaveLoadVariantProofFound')}",
        f"- failed runtime source-save load variant gates: `{list_text(summary.get('failedRuntimeSourceSaveLoadVariantGateIds'))}`",
        f"- evidence refs: {summary.get('evidenceRefCount')}",
        f"- load-only selectors: `{list_text(load.get('observedSelectors'))}`",
        f"- load-only public observed: `{list_text(load.get('observedPublicSaveSelectors'))}`",
        f"- coordinate-load selectors: `{list_text(coordinate.get('observedSelectors'))}`",
        f"- coordinate-load source/start observed: {coordinate.get('sourceSaveObserved')} / {coordinate.get('sourceStartTileObserved')}",
        f"- exit-path selectors: `{list_text(exit_path.get('observedSelectors'))}`",
        f"- exit-path public observed: `{list_text(exit_path.get('observedPublicSaveSelectors'))}`",
        f"- exit-path route/current observed: {exit_path.get('anyReachedRouteSelectorContext')} / {exit_path.get('anyReachedCurrentRoot')}",
        f"- adaptive source-ready rows: {adaptive.get('sourceReadyCount')}",
        f"- adaptive route/current observed: {adaptive.get('anyReachedRouteSelectorContext')} / {adaptive.get('anyReachedCurrentRoot')}",
        f"- adaptive trail-start source-ready rows: {adaptive_trail.get('sourceReadyCount')}",
        f"- adaptive trail-start route/current observed: {adaptive_trail.get('anyReachedRouteSelectorContext')} / {adaptive_trail.get('anyReachedCurrentRoot')}",
        f"- ready path diversion: `{ready_paths.get('diversionClassification')}`",
        f"- diversion selector context: `{diversion.get('classification')}`",
        f"- diversion selector/maps: `{diversion.get('selector')}` / `{list_text(diversion.get('fieldMaps'))}`",
        f"- diversion route-pair/source-target/current proof: {diversion.get('selectorInRoutePair')} / "
        f"{diversion.get('containsSourceMap')}/{diversion.get('containsTargetMap')} / "
        f"{diversion.get('selectedPointerPathSelectsOrStoresCurrentCount')}",
        f"- ready paths / route-current / candidate-outside: {ready_paths.get('readyPathCount')} / {ready_paths.get('routeOrCurrentReadyPathCount')} / {ready_paths.get('candidateOrOutsideReadyPathCount')}",
        f"- first non-source selectors: `{compact_json(ready_paths.get('firstNonSourceSelectorCounts'))}`",
        f"- dominant non-route selector/maps: `{ready_paths.get('dominantNonRouteSelector')}` / `{list_text(ready_paths.get('dominantNonRouteFieldMaps'))}`",
        f"- ready-path camera extent: x={ready_extent.get('minX')}..{ready_extent.get('maxX')} y={ready_extent.get('minY')}..{ready_extent.get('maxY')}",
        "",
        summary.get("conclusion") or "",
        "",
        "## Missing Evidence",
        "",
    ]
    for item in summary.get("missingEvidence") or []:
        lines.append(f"- {item}")
    lines.extend([
        "",
        "## Evidence Refs",
        "",
        "| path | fields |",
        "| --- | --- |",
    ])
    for ref in summary.get("evidenceRefs") or []:
        lines.append(f"| `{ref.get('path')}` | `{list_text(ref.get('fields'))}` |")
    lines.extend([
        "",
        "## Ready Path Diversion",
        "",
        "### Diversion Selector Context",
        "",
        f"- selector: `{diversion.get('selector')}`",
        f"- field maps: `{list_text(diversion.get('fieldMaps'))}`",
        f"- map-set aliases: `{list_text(diversion.get('aliasGroupSelectors'))}`",
        f"- contains source/target map: {diversion.get('containsSourceMap')} / {diversion.get('containsTargetMap')}",
        f"- scene adjacency rows/selector-only/strict/confirmed: {diversion.get('sceneAdjacencyRowCount')} / "
        f"{diversion.get('sceneAdjacencySelectorOnlyPairCount')} / "
        f"{diversion.get('sceneAdjacencyStrictEventBackedCount')} / "
        f"{diversion.get('sceneAdjacencyConfirmedReviewBackedCount')}",
        f"- selected pointer root/range: `{selected_path.get('rootHex')}` / `{selected_path.get('rangeHex')}`",
        f"- selected pointer current/candidates: "
        f"{selected_path.get('opcode07SelectsCurrentRootCount')}/"
        f"{selected_path.get('opcode07SelectsCurrentRangeCount')}/"
        f"{selected_path.get('opcode09StoresCurrentRootCount')}/"
        f"{selected_path.get('opcode09StoresCurrentRangeCount')}/"
        f"{selected_path.get('opcode08NearestCurrentRootProducerCount')}/"
        f"{selected_path.get('opcode08NearestCurrentRangeProducerCount')}/"
        f"{selected_path.get('promotingCandidateCount')}",
        f"- route promotion evidence found: {diversion.get('routePromotionEvidenceFound')}",
        "",
        diversion.get("conclusion") or "",
        "",
        "| source | target | selectors | occurrences | strict | confirmed | classification |",
        "| --- | --- | --- | ---: | --- | --- | --- |",
    ])
    for row in diversion.get("sceneAdjacencyRows") or []:
        lines.append(
            f"| `{row.get('source')}` | `{row.get('target')}` | `{list_text(row.get('selectors'))}` | "
            f"{row.get('occurrenceCount')} | {row.get('strictEventBacked')} | "
            f"{row.get('confirmedReviewBacked')} | `{row.get('classification')}` |"
        )
    lines.extend([
        "",
        "| family | sequence | candidate | selector path | first non-source | maps | camera extent | route/current | candidate/outside |",
        "| --- | --- | --- | --- | --- | --- | --- | --- | --- |",
    ])
    for row in ready_paths.get("rows") or []:
        extent = row.get("cameraExtent") or {}
        lines.append(
            f"| `{row.get('family')}` | `{row.get('name')}` | `{row.get('candidateName')}` | "
            f"`{list_text(row.get('selectorPath'))}` | `{row.get('firstNonSourceSelector')}` | "
            f"`{list_text(row.get('firstNonSourceFieldMaps'))}` | "
            f"x={extent.get('minX')}..{extent.get('maxX')} y={extent.get('minY')}..{extent.get('maxY')} | "
            f"{row.get('routeSelectorHitCount')}/{row.get('currentRootHitCount')} | "
            f"{row.get('candidateOrOutsideObserved')} |"
        )
    lines.extend([
        "",
        "## Load-Only Rows",
        "",
        "| sequence | samples | selectors | source 0:0 | route/current |",
        "| --- | ---: | --- | --- | --- |",
    ])
    for row in load.get("rows") or []:
        lines.append(
            f"| `{row.get('name')}` | {row.get('sampleCount')} | `{list_text(row.get('selectors'))}` | "
            f"{row.get('sourceSelectorObserved')} | {row.get('routeSelectorHitCount')}/{row.get('currentRootHitCount')} |"
        )
    lines.extend([
        "",
        "## Coordinate Load Rows",
        "",
        "| sequence | samples | selectors | camera pairs | source/start | route/current | branch state |",
        "| --- | ---: | --- | --- | --- | --- | --- |",
    ])
    for row in coordinate.get("rows") or []:
        camera_pairs = "; ".join(
            f"{pair.get('x')},{pair.get('y')}x{pair.get('count')}"
            for pair in row.get("cameraPairs") or []
        )
        lines.append(
            f"| `{row.get('name')}` | {row.get('sampleCount')} | `{list_text(row.get('selectors'))}` | "
            f"`{camera_pairs or '-'}` | {row.get('sourceSelectorObserved')}/{row.get('cameraSourceStartObserved')} | "
            f"{row.get('routeSelectorHitCount')}/{row.get('currentRootHitCount')} | "
            f"{'all-zero' if row.get('branchStateAllZero') else 'mixed'} |"
        )
    lines.extend([
        "",
        "## Exit-Path Rows",
        "",
        "| sequence | samples | selectors | route/current |",
        "| --- | ---: | --- | --- |",
    ])
    for row in exit_path.get("rows") or []:
        lines.append(
            f"| `{row.get('name')}` | {row.get('sampleCount')} | `{list_text(row.get('selectors'))}` | "
            f"{row.get('routeSelectorHitCount')}/{row.get('currentRootHitCount')} |"
        )
    lines.extend([
        "",
        "## Exit Candidates",
        "",
        "| sequence | candidate | samples | selectors | candidate/outside | actor/trail candidate | route/current | branch state |",
        "| --- | --- | ---: | --- | --- | --- | --- | --- |",
    ])
    for row in exit_path.get("candidateRows") or []:
        candidate = row.get("candidateTile") or {}
        outside = row.get("outsideTile") or {}
        actor_trail = bool(row.get("actorCandidateSlots") or row.get("trailCandidateSlots"))
        lines.append(
            f"| `{row.get('name')}` | `{candidate.get('x')},{candidate.get('y')}` -> "
            f"`{outside.get('x')},{outside.get('y')}` {row.get('candidateSide')} | "
            f"{row.get('sampleCount')} | `{list_text(row.get('selectors'))}` | "
            f"{row.get('cameraCandidateObserved')}/{row.get('cameraOutsideObserved')} | "
            f"{actor_trail} | {row.get('routeSelectorHitCount')}/{row.get('currentRootHitCount')} | "
            f"{'all-zero' if row.get('branchStateAllZero') else 'mixed'} |"
        )
    lines.extend([
        "",
        "## Adaptive Exit Rows",
        "",
        "| sequence | source ready | samples | selectors | camera pairs | candidate/outside | route/current | branch state |",
        "| --- | --- | ---: | --- | --- | --- | --- | --- |",
    ])
    for row in adaptive.get("rows") or []:
        camera_pairs = "; ".join(
            f"{pair.get('x')},{pair.get('y')}x{pair.get('count')}"
            for pair in row.get("cameraPairs") or []
        )
        lines.append(
            f"| `{row.get('name')}` | {row.get('sourceReady')} | {row.get('sampleCount')} | "
            f"`{list_text(row.get('selectors'))}` | `{camera_pairs or '-'}` | "
            f"{row.get('cameraCandidateObserved')}/{row.get('cameraOutsideObserved')} | "
            f"{row.get('routeSelectorHitCount')}/{row.get('currentRootHitCount')} | "
            f"{'all-zero' if row.get('branchStateAllZero') else 'mixed'} |"
        )
    lines.extend([
        "",
        "## Adaptive Trail-Start Rows",
        "",
        "| sequence | source ready | path steps | samples | selectors | camera pairs | candidate/outside | actor/trail candidate | route/current | branch state |",
        "| --- | --- | ---: | ---: | --- | --- | --- | --- | --- | --- |",
    ])
    for row in adaptive_trail.get("rows") or []:
        camera_pairs = "; ".join(
            f"{pair.get('x')},{pair.get('y')}x{pair.get('count')}"
            for pair in row.get("cameraPairs") or []
        )
        actor_trail = bool(row.get("actorCandidateSlots") or row.get("trailCandidateSlots"))
        lines.append(
            f"| `{row.get('name')}` | {row.get('sourceReady')} | {row.get('pathStepCount')} | "
            f"{row.get('sampleCount')} | `{list_text(row.get('selectors'))}` | `{camera_pairs or '-'}` | "
            f"{row.get('cameraCandidateObserved')}/{row.get('cameraOutsideObserved')} | {actor_trail} | "
            f"{row.get('routeSelectorHitCount')}/{row.get('currentRootHitCount')} | "
            f"{'all-zero' if row.get('branchStateAllZero') else 'mixed'} |"
        )
    return "\n".join(lines) + "\n"


def html_page(summary: dict[str, Any]) -> str:
    return (
        "<!doctype html><meta charset=\"utf-8\"><title>Runtime Source Save Load Variant Context</title>"
        "<style>body{font-family:sans-serif;line-height:1.4}table{border-collapse:collapse}"
        "td,th{border:1px solid #ccc;padding:4px 6px}code{background:#f3f3f3;padding:1px 3px}</style>"
        f"<pre>{html.escape(markdown(summary))}</pre>"
    )


def write_outputs(summary: dict[str, Any], out_dir: Path = OUT, html_out: Path | None = None) -> None:
    out_dir.mkdir(parents=True, exist_ok=True)
    (out_dir / "runtime_source_save_load_variant_context.json").write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    if html_out is not None:
        html_out.parent.mkdir(parents=True, exist_ok=True)
        html_out.write_text(html_page(summary), encoding="utf-8")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--html-out",
        type=Path,
        default=None,
        help="Optional HTML review path. By default only the JSON evidence is written.",
    )
    args = parser.parse_args()
    load_variant_poll = load_json(LOAD_VARIANT_POLL)
    load_coordinate_poll = load_json(LOAD_COORDINATE_POLL)
    load_confirmed_exit_poll = load_json(LOAD_CONFIRMED_EXIT_POLL)
    adaptive_exit_poll = load_json(ADAPTIVE_EXIT_POLL)
    adaptive_trail_start_poll = load_json(ADAPTIVE_TRAIL_START_POLL)
    mapset_aliases = load_json(MAPSET_ALIASES)
    scene_adjacency = load_json(SCENE_ADJACENCY_INDEX)
    selected_pointer_paths = load_json(GLOBAL_SELECTED_POINTER_PATHS)
    summary = build_summary(
        load_variant_poll,
        load_coordinate_poll,
        load_confirmed_exit_poll,
        adaptive_exit_poll,
        adaptive_trail_start_poll,
        mapset_aliases,
        scene_adjacency,
        selected_pointer_paths,
    )
    write_outputs(summary, OUT, args.html_out)
    print(f"wrote runtime source save load variant context -> {OUT / 'runtime_source_save_load_variant_context.json'}")


if __name__ == "__main__":
    main()
