#!/usr/bin/env python3
"""Summarize the current frontier reader branch outcomes."""
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"
SOURCE = "map1_01a"
TARGET = "map2_02d"
READER_HEX = "0x00542b0c"
FAILED_FRONTIER_READER_GATE_IDS = [
    "normal-runtime-reader-execution",
    "resource-payload-strict-hotspot",
    "independent-strict-transition-evidence",
]
FRONTIER_READER_MISSING_EVIDENCE = [
    "normal runtime selector/root execution reaches reader 0x00542b0c with real route state",
    "selected resource payload decodes to a strict map1_01a source hotspot",
    "independent strict event/coordinate evidence for map1_01a -> map2_02d",
]
FRONTIER_READER_EVIDENCE_REFS = [
    {
        "path": "out/save_selector_scene_list_context.json",
        "fields": ["currentFrontier", "branchSteps", "evidenceRefs", "evidenceRefCount"],
    },
    {
        "path": "out/save_selector_branch_selector_equation.json",
        "fields": ["predecessorFillHypothesis", "activeFlagEffect", "readerHandlerVaHex"],
    },
    {
        "path": "out/map1_01a_scene_payload_context.json",
        "fields": ["payloads", "classification", "promotionEvidence"],
    },
    {
        "path": "out/save_selector_opcode2c_route_pair_context.json",
        "fields": ["correctedTraceReachesReaderCount", "routePairDescriptorCount", "proofFound"],
    },
]


def load_json(path: Path, fallback: Any) -> Any:
    if not path.exists():
        return fallback
    return json.loads(path.read_text(encoding="utf-8"))


def u32_from_hex(value: str | None) -> int | None:
    if not isinstance(value, str):
        return None
    return int(value, 16)


def low_byte(value_hex: str | None) -> int | None:
    value = u32_from_hex(value_hex)
    return value & 0xFF if value is not None else None


def stream_byte(value_hex: str | None, offset: int) -> int | None:
    value = u32_from_hex(value_hex)
    if value is None:
        return None
    return (value >> (offset * 8)) & 0xFF


def kind_label(kind: dict | None) -> str:
    kind = kind or {}
    return kind.get("cns") or kind.get("targetVaHex") or kind.get("kind") or "-"


def payload_by_va(scene_payload_context: dict) -> dict[str, dict]:
    return {
        row.get("payloadVaHex"): row
        for row in scene_payload_context.get("payloads") or []
        if row.get("payloadVaHex")
    }


def window_by_va(scene_list_context: dict) -> dict[str, dict]:
    current = scene_list_context.get("currentFrontier") or {}
    return {
        row.get("vaHex"): row
        for row in current.get("window") or []
        if row.get("vaHex")
    }


def add_hex(value_hex: str | None, delta: int) -> str | None:
    value = u32_from_hex(value_hex)
    if value is None:
        return None
    return f"0x{value + delta:08x}"


def sibling_gate_rows(scene_list_context: dict) -> list[dict]:
    current = scene_list_context.get("currentFrontier") or {}
    window = current.get("window") or []
    by_va = window_by_va(scene_list_context)
    first_source = ((current.get("branchSteps") or [{}])[0].get("nearestSourceRecordAfterBranch") or {}).get("recordVaHex")
    first_source_va = u32_from_hex(first_source)
    rows = []
    for row in window:
        va_hex = row.get("vaHex")
        va = u32_from_hex(va_hex)
        if va is None or (first_source_va is not None and va >= first_source_va):
            continue
        if low_byte(row.get("valueHex")) != 0x11:
            continue
        target = by_va.get(add_hex(va_hex, 4) or "")
        fallthrough = by_va.get(add_hex(va_hex, 8) or "")
        value_hex = row.get("valueHex")
        table = "secondaryBranchState" if (stream_byte(value_hex, 1) or 0) != 0 else "primaryBranchState"
        offset = stream_byte(value_hex, 2)
        rows.append({
            "branchVaHex": va_hex,
            "valueHex": value_hex,
            "stateTable": table,
            "selectionBufferOffsetHex": f"0x{offset:02x}" if offset is not None else None,
            "falseTargetVaHex": target.get("valueHex") if target else None,
            "falseTargetKind": target.get("valueKind") if target else {},
            "falseTargetIsFieldMap": (target.get("valueKind") or {}).get("isFieldMap") is True if target else False,
            "falseTargetIsResource": (target.get("valueKind") or {}).get("isResource") is True if target else False,
            "trueFallthroughVaHex": fallthrough.get("vaHex") if fallthrough else None,
            "trueFallthroughValueHex": fallthrough.get("valueHex") if fallthrough else None,
            "trueFallthroughKind": fallthrough.get("valueKind") if fallthrough else {},
            "trueFallthroughHandlerSection": ((fallthrough or {}).get("handlerCandidate") or {}).get("handlerSection"),
            "trueFallthroughLooksExecutable": ((fallthrough or {}).get("handlerCandidate") or {}).get("isCodeHandler") is True,
        })
    return rows


def build_summary(
    scene_list_context: dict,
    branch_selector_equation: dict,
    scene_payload_context: dict,
    opcode2c_context: dict,
) -> dict:
    current = scene_list_context.get("currentFrontier") or {}
    branch = next(
        (row for row in current.get("branchSteps") or [] if row.get("streamVaHex") == READER_HEX),
        (current.get("branchSteps") or [{}])[0],
    )
    payloads = payload_by_va(scene_payload_context)
    fallthrough_payload = payloads.get(branch.get("fallthroughValueHex")) or {}
    predecessor = branch_selector_equation.get("predecessorFillHypothesis") or {}
    active = branch_selector_equation.get("activeFlagEffect") or {}
    predecessor_selects_fallthrough = predecessor.get("allStartsPassReader") is True
    pass_outcome = {
        "conditionValue": 1,
        "outcome": "fallthrough",
        "nextStreamVaHex": branch.get("fallthroughVaHex"),
        "valueHex": branch.get("fallthroughValueHex"),
        "valueKind": branch.get("fallthroughValueKind") or {},
        "handlerSection": (branch.get("fallthroughHandlerCandidate") or {}).get("handlerSection"),
        "looksExecutable": branch.get("fallthroughLooksExecutable") is True,
        "payloadClassification": fallthrough_payload.get("classification"),
        "payloadPromotionEvidence": fallthrough_payload.get("promotionEvidence"),
        "payloadInBoundsPointCount": (fallthrough_payload.get("pointScan") or {}).get("inBoundsPointCount"),
        "payloadRangeTextRefCount": fallthrough_payload.get("rangeTextRefCount"),
    }
    fail_outcome = {
        "conditionValue": "not-1",
        "outcome": "jump",
        "targetVaHex": branch.get("branchTargetHex"),
        "valueKind": branch.get("branchTargetValueKind") or {},
        "targetIsResource": branch.get("branchTargetIsResource") is True,
        "targetIsFieldMap": (branch.get("branchTargetValueKind") or {}).get("isFieldMap") is True,
    }
    siblings = sibling_gate_rows(scene_list_context)
    conclusion = (
        "The corrected route-pair descriptor trace reaches the 0x00542b0c reader, but the reader does not "
        "directly select map2_02d. If the inherited predecessor-fill hypothesis is true, opcode 0x11 falls "
        "through to 0x00542b14, whose value points at a sprite/rect-like payload with no in-bounds source "
        "hotspot evidence. If the condition is false, it jumps to the character resource cara_01.cns. "
        "The nearby sibling 0x11 gates likewise select character resources or payload descriptors before "
        "the source/target scene records. This keeps the frontier as resource/scene-list evidence, not a "
        "confirmed normal map transition."
    )
    return {
        "source": SOURCE,
        "target": TARGET,
        "readerVaHex": READER_HEX,
        "readerValueHex": branch.get("valueHex"),
        "readerHandlerVaHex": branch_selector_equation.get("readerHandlerVaHex"),
        "condition": branch.get("condition"),
        "selectionBufferOffsetHex": branch.get("selectionBufferOffsetHex"),
        "stateTable": branch.get("stateTable"),
        "routePairCorrectedTraceReachesReaderCount": opcode2c_context.get("correctedTraceReachesReaderCount"),
        "routePairDescriptorCount": opcode2c_context.get("routePairDescriptorCount"),
        "predecessorHypothesisSelector": predecessor.get("predecessorSelector"),
        "predecessorHypothesisFillHex": predecessor.get("fillValueHex"),
        "predecessorAllStartsPassReader": predecessor.get("allStartsPassReader"),
        "priorSelectionBufferStillPrimaryBlocker": active.get("priorSelectionBufferStillPrimaryBlockerUnderPredecessorHypothesis"),
        "predecessorHypothesisOutcome": "fallthrough" if predecessor_selects_fallthrough else "unproven",
        "passOutcome": pass_outcome,
        "failOutcome": fail_outcome,
        "siblingGateCountBeforeSourceRecord": len(siblings),
        "siblingResourceGateCount": sum(1 for row in siblings if row.get("falseTargetIsResource")),
        "siblingFieldMapTargetCount": sum(1 for row in siblings if row.get("falseTargetIsFieldMap")),
        "siblingExecutableFallthroughCount": sum(1 for row in siblings if row.get("trueFallthroughLooksExecutable")),
        "siblingGates": siblings,
        "nearestSourceRecordAfterReader": branch.get("nearestSourceRecordAfterBranch"),
        "nearestTargetRecordAfterReader": branch.get("nearestTargetRecordAfterBranch"),
        "classification": branch.get("classification"),
        "proofFound": False,
        "frontierReaderRuntimeProofFound": False,
        "frontierReaderStrictHotspotProofFound": False,
        "failedFrontierReaderGateIds": FAILED_FRONTIER_READER_GATE_IDS,
        "missingEvidence": FRONTIER_READER_MISSING_EVIDENCE,
        "evidenceRefs": FRONTIER_READER_EVIDENCE_REFS,
        "evidenceRefCount": len(FRONTIER_READER_EVIDENCE_REFS),
        "strictHotspotFound": False,
        "runtimeSelectionProven": False,
        "promotionStatus": "blocked",
        "conclusion": conclusion,
        "remainingProofs": [
            "prove normal runtime selector/root execution reaches this reader with real route state",
            "decode the selected resource payload into a strict map1_01a source hotspot, if one exists",
            "or find independent strict event/coordinate evidence for map1_01a -> map2_02d",
        ],
    }


def markdown(summary: dict) -> str:
    pass_outcome = summary.get("passOutcome") or {}
    fail_outcome = summary.get("failOutcome") or {}
    lines = [
        "# Save Selector Frontier Reader Branch Context",
        "",
        f"- route: `{summary.get('source')} -> {summary.get('target')}`",
        f"- reader: `{summary.get('readerVaHex')}` `{summary.get('readerValueHex')}` via `{summary.get('readerHandlerVaHex')}`",
        f"- condition: `{summary.get('condition')}`",
        f"- corrected route-pair traces reaching reader: {summary.get('routePairCorrectedTraceReachesReaderCount')}/{summary.get('routePairDescriptorCount')}",
        f"- predecessor hypothesis: `{summary.get('predecessorHypothesisSelector')}` fill `{summary.get('predecessorHypothesisFillHex')}` all starts pass={summary.get('predecessorAllStartsPassReader')}",
        f"- predecessor hypothesis outcome: `{summary.get('predecessorHypothesisOutcome')}`",
        f"- proof found: {summary.get('proofFound')}",
        f"- frontier reader runtime proof found: {summary.get('frontierReaderRuntimeProofFound')}",
        f"- frontier reader strict hotspot proof found: {summary.get('frontierReaderStrictHotspotProofFound')}",
        f"- failed frontier reader gates: {', '.join(summary.get('failedFrontierReaderGateIds') or []) or '-'}",
        f"- missing evidence count: {len(summary.get('missingEvidence') or [])}",
        f"- evidence refs: {summary.get('evidenceRefCount')}",
        f"- strict hotspot found: {summary.get('strictHotspotFound')}",
        f"- runtime selection proven: {summary.get('runtimeSelectionProven')}",
        f"- promotion status: `{summary.get('promotionStatus')}`",
        "",
        summary.get("conclusion") or "",
        "",
        "## Reader Outcomes",
        "",
        "| condition value | outcome | target/value | kind | executable | payload class | promotion evidence |",
        "| --- | --- | --- | --- | --- | --- | --- |",
        f"| 1 | {pass_outcome.get('outcome')} | `{pass_outcome.get('nextStreamVaHex')}` -> `{pass_outcome.get('valueHex')}` | {kind_label(pass_outcome.get('valueKind'))} | {pass_outcome.get('looksExecutable')} | {pass_outcome.get('payloadClassification') or '-'} | {pass_outcome.get('payloadPromotionEvidence')} |",
        f"| not 1 | {fail_outcome.get('outcome')} | `{fail_outcome.get('targetVaHex')}` | {kind_label(fail_outcome.get('valueKind'))} | - | resource={fail_outcome.get('targetIsResource')} fieldMap={fail_outcome.get('targetIsFieldMap')} | False |",
        "",
        "## Sibling Gates Before Source Record",
        "",
        f"- gate count: {summary.get('siblingGateCountBeforeSourceRecord')}",
        f"- resource target count: {summary.get('siblingResourceGateCount')}",
        f"- field-map target count: {summary.get('siblingFieldMapTargetCount')}",
        f"- executable fallthrough count: {summary.get('siblingExecutableFallthroughCount')}",
        "",
        "| branch | offset | false target | false kind | true fallthrough | true kind | true executable |",
        "| --- | --- | --- | --- | --- | --- | --- |",
    ]
    for row in summary.get("siblingGates") or []:
        lines.append(
            f"| `{row.get('branchVaHex')}` | `{row.get('selectionBufferOffsetHex')}` | "
            f"`{row.get('falseTargetVaHex')}` | {kind_label(row.get('falseTargetKind'))} | "
            f"`{row.get('trueFallthroughVaHex')}` -> `{row.get('trueFallthroughValueHex')}` | "
            f"{kind_label(row.get('trueFallthroughKind'))} | {row.get('trueFallthroughLooksExecutable')} |"
        )
    lines.extend(["", "## Remaining Proofs", ""])
    lines.extend(f"- {item}" for item in summary.get("remainingProofs") or [])
    lines.extend(["", "## Missing Evidence", ""])
    lines.extend(f"- {item}" for item in summary.get("missingEvidence") or [])
    lines.append("")
    return "\n".join(lines)


def html_page(summary: dict) -> str:
    pass_outcome = summary.get("passOutcome") or {}
    fail_outcome = summary.get("failOutcome") or {}
    sibling_rows = []
    for row in summary.get("siblingGates") or []:
        sibling_rows.append(
            "<tr>"
            f"<td><code>{html.escape(str(row.get('branchVaHex')))}</code></td>"
            f"<td><code>{html.escape(str(row.get('selectionBufferOffsetHex')))}</code></td>"
            f"<td><code>{html.escape(str(row.get('falseTargetVaHex')))}</code></td>"
            f"<td>{html.escape(kind_label(row.get('falseTargetKind')))}</td>"
            f"<td><code>{html.escape(str(row.get('trueFallthroughVaHex')))}</code> -> <code>{html.escape(str(row.get('trueFallthroughValueHex')))}</code></td>"
            f"<td>{html.escape(kind_label(row.get('trueFallthroughKind')))}</td>"
            f"<td>{row.get('trueFallthroughLooksExecutable')}</td>"
            "</tr>"
        )
    proofs = "".join(f"<li>{html.escape(item)}</li>" for item in summary.get("remainingProofs") or [])
    failed_gates = "".join(
        f"<li>{html.escape(item)}</li>" for item in summary.get("failedFrontierReaderGateIds") or []
    )
    missing = "".join(f"<li>{html.escape(item)}</li>" for item in summary.get("missingEvidence") or [])
    return "\n".join([
        "<!doctype html>",
        '<html lang="en">',
        "<head>",
        '  <meta charset="utf-8">',
        '  <meta name="viewport" content="width=device-width, initial-scale=1">',
        "  <title>Save Selector Frontier Reader Branch Context</title>",
        "  <style>body{font-family:system-ui,sans-serif;background:#111;color:#eee;margin:24px}table{border-collapse:collapse;width:100%;max-width:1280px;margin-bottom:24px}td,th{border:1px solid #333;padding:6px 8px;text-align:left;vertical-align:top}th{background:#1f1f1f}code{color:#9bd4ff}</style>",
        "</head>",
        "<body>",
        "  <h1>Save Selector Frontier Reader Branch Context</h1>",
        f"  <p>route <code>{html.escape(str(summary.get('source')))} -&gt; {html.escape(str(summary.get('target')))}</code>; reader <code>{html.escape(str(summary.get('readerVaHex')))}</code>; corrected route-pair traces reaching reader <code>{summary.get('routePairCorrectedTraceReachesReaderCount')}/{summary.get('routePairDescriptorCount')}</code>; predecessor hypothesis outcome <code>{html.escape(str(summary.get('predecessorHypothesisOutcome')))}</code>; promotion status <code>{html.escape(str(summary.get('promotionStatus')))}</code>.</p>",
        f"  <p>proofFound <code>{summary.get('proofFound')}</code>; frontierReaderRuntimeProofFound <code>{summary.get('frontierReaderRuntimeProofFound')}</code>; frontierReaderStrictHotspotProofFound <code>{summary.get('frontierReaderStrictHotspotProofFound')}</code>; missingEvidenceCount <code>{len(summary.get('missingEvidence') or [])}</code>; evidence refs <code>{summary.get('evidenceRefCount')}</code>.</p>",
        f"  <p>{html.escape(summary.get('conclusion') or '')}</p>",
        f"  <h2>Failed Frontier Reader Gates</h2><ul>{failed_gates}</ul>",
        f"  <h2>Missing Evidence</h2><ul>{missing}</ul>",
        "  <h2>Reader Outcomes</h2>",
        "  <table><thead><tr><th>condition</th><th>outcome</th><th>target/value</th><th>kind</th><th>executable</th><th>payload class</th><th>promotion evidence</th></tr></thead>",
        "  <tbody>",
        f"    <tr><td>1</td><td>{html.escape(str(pass_outcome.get('outcome')))}</td><td><code>{html.escape(str(pass_outcome.get('nextStreamVaHex')))}</code> -> <code>{html.escape(str(pass_outcome.get('valueHex')))}</code></td><td>{html.escape(kind_label(pass_outcome.get('valueKind')))}</td><td>{pass_outcome.get('looksExecutable')}</td><td>{html.escape(str(pass_outcome.get('payloadClassification') or '-'))}</td><td>{pass_outcome.get('payloadPromotionEvidence')}</td></tr>",
        f"    <tr><td>not 1</td><td>{html.escape(str(fail_outcome.get('outcome')))}</td><td><code>{html.escape(str(fail_outcome.get('targetVaHex')))}</code></td><td>{html.escape(kind_label(fail_outcome.get('valueKind')))}</td><td>-</td><td>resource={fail_outcome.get('targetIsResource')} fieldMap={fail_outcome.get('targetIsFieldMap')}</td><td>False</td></tr>",
        "  </tbody></table>",
        "  <h2>Sibling Gates Before Source Record</h2>",
        f"  <p>gate count: <code>{summary.get('siblingGateCountBeforeSourceRecord')}</code>; resource target count: <code>{summary.get('siblingResourceGateCount')}</code>; field-map target count: <code>{summary.get('siblingFieldMapTargetCount')}</code>; executable fallthrough count: <code>{summary.get('siblingExecutableFallthroughCount')}</code>.</p>",
        "  <table><thead><tr><th>branch</th><th>offset</th><th>false target</th><th>false kind</th><th>true fallthrough</th><th>true kind</th><th>true executable</th></tr></thead>",
        f"  <tbody>{''.join(sibling_rows)}</tbody></table>",
        "  <h2>Remaining Proofs</h2>",
        f"  <ul>{proofs}</ul>",
        "</body>",
        "</html>",
        "",
    ])


def write_outputs(summary: dict, out_dir: Path = OUT) -> None:
    out_dir.mkdir(parents=True, exist_ok=True)
    (out_dir / "save_selector_frontier_reader_branch_context.json").write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out-dir", type=Path, default=OUT)
    args = parser.parse_args()
    summary = build_summary(
        load_json(args.out_dir / "save_selector_scene_list_context.json", {}),
        load_json(args.out_dir / "save_selector_branch_selector_equation.json", {}),
        load_json(args.out_dir / "map1_01a_scene_payload_context.json", {}),
        load_json(args.out_dir / "save_selector_opcode2c_route_pair_context.json", {}),
    )
    write_outputs(summary, args.out_dir)
    print(f"wrote frontier reader branch context -> {args.out_dir / 'save_selector_frontier_reader_branch_context.json'}")


if __name__ == "__main__":
    main()
