#!/usr/bin/env python3
"""Apply the strongest predecessor secondary-state fill to the current blocker equation."""
from __future__ import annotations

import argparse
import html
import json
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "out"


def simulate_opcode12_selected_slot(table: list[int], start: int) -> int:
    slot = start & 0xFF
    for _ in range(12):
        slot = slot - 1 if slot else 0x0B
        if table[slot]:
            break
    for _ in range(12):
        slot = 0 if slot + 1 >= 0x0C else slot + 1
        if table[slot]:
            break
    return slot


def build_summary() -> dict:
    table = [1, 1] + [0] * 10
    outcomes = []
    for start in range(12):
        selected = simulate_opcode12_selected_slot(table, start)
        outcomes.append({
            "startSlot": start,
            "selectedSlot": selected,
            "selectedValue": table[selected],
            "frontierReaderFallsThrough": table[selected] == 1,
        })
    conclusion = (
        "If predecessor 1:0 leaves the secondaryBranchState table as produced by opcode 0x10 value 0x00000210, "
        "then the current 2:0 opcode 0x12 writer selects slot 0 or 1 and the 0x00542b0c reader condition "
        "secondaryBranchState[selectionBuffer[0x20]] == 1 would pass for every possible 12-slot start value. "
        "This is still not enough to promote map1_01a->map2_02d: execution order/state persistence from 1:0 to 2:0 "
        "and a strict map1_01a source hotspot remain unproven."
    )
    return {
        "predecessorSelector": "1:0",
        "predecessorRootHex": "0x00478364",
        "predecessorFillVas": ["0x004844d0", "0x004844d8"],
        "fillValueHex": "0x00000210",
        "fillMeaning": "opcode 0x10 uses secondaryBranchState and helper case 0; helper 0x00410de5 writes first 2 slots to 1 and remaining 10 slots to 0.",
        "currentSelector": "2:0",
        "currentWriterVaHex": "0x005428bc",
        "currentReaderVaHex": "0x00542b0c",
        "secondaryBranchStateAfterFill": table,
        "outcomes": outcomes,
        "allStartsPassReader": all(row["frontierReaderFallsThrough"] for row in outcomes),
        "promotionStatus": "blocked",
        "remainingBlockers": [
            "prove predecessor 1:0 actually executes before current selector 2:0 in the route",
            "prove secondaryBranchState is not overwritten before 0x005428bc/0x00542b0c",
            "find strict map1_01a source coordinate or hotspot",
        ],
        "conclusion": conclusion,
    }


def markdown(summary: dict) -> str:
    lines = [
        "# Save Selector Predecessor State Effect",
        "",
        f"- predecessor: `{summary['predecessorSelector']}` root `{summary['predecessorRootHex']}`",
        f"- fill sites: {', '.join(f'`{va}`' for va in summary['predecessorFillVas'])}",
        f"- fill value: `{summary['fillValueHex']}`",
        f"- fill meaning: {summary['fillMeaning']}",
        f"- current writer/reader: `{summary['currentWriterVaHex']}` / `{summary['currentReaderVaHex']}`",
        f"- all starts pass reader: {summary['allStartsPassReader']}",
        f"- promotion status: {summary['promotionStatus']}",
        "",
        summary["conclusion"],
        "",
        "## Outcomes",
        "",
        "| start slot | selected slot | selected value | reader falls through |",
        "| ---: | ---: | ---: | --- |",
    ]
    for row in summary["outcomes"]:
        lines.append(
            f"| {row['startSlot']} | {row['selectedSlot']} | {row['selectedValue']} | "
            f"{'yes' if row['frontierReaderFallsThrough'] else 'no'} |"
        )
    lines.extend(["", "## Remaining Blockers", ""])
    lines.extend(f"- {item}" for item in summary["remainingBlockers"])
    lines.append("")
    return "\n".join(lines)


def html_page(summary: dict) -> str:
    rows = "\n".join(
        "<tr>"
        f"<td>{row['startSlot']}</td>"
        f"<td>{row['selectedSlot']}</td>"
        f"<td>{row['selectedValue']}</td>"
        f"<td>{'yes' if row['frontierReaderFallsThrough'] else 'no'}</td>"
        "</tr>"
        for row in summary["outcomes"]
    )
    blockers = "".join(f"<li>{html.escape(item)}</li>" for item in summary["remainingBlockers"])
    return "\n".join([
        "<!doctype html><meta charset=\"utf-8\"><title>Save Selector Predecessor State Effect</title>",
        "<style>body{font-family:system-ui,sans-serif;background:#111;color:#eee;max-width:1100px;margin:24px auto}table{border-collapse:collapse}td,th{border:1px solid #444;padding:6px 8px}code{color:#9bd4ff}</style>",
        "<h1>Save Selector Predecessor State Effect</h1>",
        f"<p>Predecessor <code>{summary['predecessorSelector']}</code> root <code>{summary['predecessorRootHex']}</code>, fill value <code>{summary['fillValueHex']}</code>.</p>",
        f"<p>Fill sites: {', '.join('<code>' + html.escape(va) + '</code>' for va in summary['predecessorFillVas'])}</p>",
        f"<p>all starts pass reader: {summary['allStartsPassReader']}; promotion status: {html.escape(summary['promotionStatus'])}</p>",
        f"<p>{html.escape(summary['fillMeaning'])}</p>",
        f"<p>{html.escape(summary['conclusion'])}</p>",
        "<table><thead><tr><th>start slot</th><th>selected slot</th><th>selected value</th><th>reader falls through</th></tr></thead><tbody>",
        rows,
        "</tbody></table>",
        "<h2>Remaining Blockers</h2>",
        f"<ul>{blockers}</ul>",
    ])


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


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--out-dir", type=Path, default=OUT)
    args = parser.parse_args()
    summary = build_summary()
    write_outputs(summary, args.out_dir)
    print(f"wrote predecessor state effect -> {args.out_dir / 'save_selector_predecessor_state_effect.json'}")


if __name__ == "__main__":
    main()
