"""Reproduce Knowing Enough Essai 04 with Python 3.9+ and the standard library.

In the source checkout: python3 essai-04/evidence/replay.py --check
From the public download: python3 replay.py --online --check
"""

import argparse
from collections import defaultdict, deque
import copy
import hashlib
from itertools import product
import json
from pathlib import Path
from urllib.parse import urljoin
from urllib.request import urlopen

ROOT = Path(__file__).resolve().parent
PUBLIC_ROOT = "https://experimentsin.ai/knowing-enough/essai-04/evidence/"
MAX_STATES = 10_000
MAX_EDGES = 100_000


INPUTS = [
    ("inputs/rotunda.json", "ad82e113c35e3a92d5f2dedd6ee87ab052bff52f7de1a646ee43fc66112ee5a2"),
    ("inputs/gimmer.json", "f90953a7b688bad83f1afa3aac49f227de3083205b5cdbcc0c3ee558bddc8909"),
    (
        "../../essai-02/results.json",
        "014986d59b9cc7db703e52b63388d1ac12f5313fcbd9c3549200f34ad80064b4",
    ),
]
RESULT_SHA256 = "f7a4ad7237e816de567df84b42fbd1e40bf268c08e760e1fed5003f683ba5a8d"


# Observation and labelled-step checker.


def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False)


def validate(model, partition):
    if model.get("complete") is not True:
        raise ValueError(
            "The supplied state/transition enumeration is incomplete or not certified complete."
        )
    rows = model.get("states", [])
    if not rows or len(rows) > MAX_STATES:
        raise ValueError("Empty model or explicit state bound exceeded.")
    states = {}
    for row in rows:
        sid = row.get("id")
        if not isinstance(sid, str) or sid in states:
            raise ValueError("Every state needs a unique string ID.")
        if "observation" not in row or not isinstance(row.get("edges"), list):
            raise ValueError("Every state needs a declared observation and explicit edge list.")
        canonical(row["observation"])
        states[sid] = row
    if set(partition) != set(states):
        raise ValueError(
            "Summary domain differs from the admitted states; an explicit extension is required."
        )
    for value in partition.values():
        canonical(value)
    if sum(len(s["edges"]) for s in rows) > MAX_EDGES:
        raise ValueError("Explicit edge bound exceeded.")
    for row in rows:
        for edge in row["edges"]:
            if not isinstance(edge.get("action"), str) or edge.get("to") not in states:
                raise ValueError("Every edge needs a string action and an admitted target.")
    initial = model.get("initial", [])
    if not initial or any(s not in states for s in initial):
        raise ValueError("Declare one or more admitted initial states.")
    return states


def normalise(partition):
    labels = {}
    result = {}
    for sid in sorted(partition):
        value = canonical(partition[sid])
        if value not in labels:
            labels[value] = len(labels)
        result[sid] = labels[value]
    return result


def successors(row, partition):
    return tuple(sorted({(e["action"], partition[e["to"]]) for e in row["edges"]}))


def path_to(model, target):
    rows = {s["id"]: s for s in model["states"]}
    paths = {s: [] for s in model["initial"]}
    todo = deque(model["initial"])
    while todo:
        sid = todo.popleft()
        if sid == target:
            return paths[sid]
        for edge in rows[sid]["edges"]:
            if edge["to"] not in paths:
                paths[edge["to"]] = paths[sid] + [{"from": sid, **edge}]
                todo.append(edge["to"])
    return None


def diagnose(model, partition):
    try:
        states = validate(model, partition)
        classes = normalise(partition)
    except (ValueError, TypeError, KeyError) as exc:
        return {
            "status": "unresolved",
            "reason": str(exc),
            "guarantee": "strong-labelled-step-and-observation",
        }
    representatives = {}
    for sid in sorted(states):
        block = classes[sid]
        if block not in representatives:
            representatives[block] = sid
            continue
        other = representatives[block]
        left, right = states[other], states[sid]
        witness = None
        if canonical(left["observation"]) != canonical(right["observation"]):
            witness = {
                "kind": "observation",
                "left_observation": left["observation"],
                "right_observation": right["observation"],
            }
        else:
            lsucc, rsucc = set(successors(left, classes)), set(successors(right, classes))
            if lsucc != rsucc:
                side = "left" if lsucc - rsucc else "right"
                action, destination = sorted(
                    (lsucc - rsucc) if side == "left" else (rsucc - lsucc)
                )[0]
                witness = {
                    "kind": "step",
                    "action": action,
                    "target_class": destination,
                    "available_from": side,
                    "left_successor_classes": sorted(b for a, b in lsucc if a == action),
                    "right_successor_classes": sorted(b for a, b in rsucc if a == action),
                }
        if witness:
            witness.update(
                {
                    "left": other,
                    "right": sid,
                    "summary_class": block,
                    "left_path": path_to(model, other),
                    "right_path": path_to(model, sid),
                }
            )
            return {
                "status": "insufficient",
                "guarantee": "strong-labelled-step-and-observation",
                "witness": witness,
            }
    return {
        "status": "sufficient",
        "guarantee": "strong-labelled-step-and-observation",
        "states": len(states),
        "classes": len(set(classes.values())),
    }


def refine(model, partition):
    """Coarsest stable refinement of this partition, by ordinary signature splits."""
    states = validate(model, partition)
    current = normalise(partition)
    history = []
    while True:
        signatures = {
            s: (current[s], states[s]["observation"], successors(states[s], current))
            for s in states
        }
        refined = normalise(signatures)
        before, after = len(set(current.values())), len(set(refined.values()))
        history.append({"before": before, "after": after})
        if after == before:
            return {"partition": refined, "rounds": history, "classes": after}
        current = refined


def one_step_policy(worlds, partition, all_actions):
    """Uniform successful one-step choices. No sequential-planning claim."""
    ids = {w["id"] for w in worlds}
    if len(ids) != len(worlds) or ids != set(partition) or not worlds:
        raise ValueError("One-step worlds and summary domain must match exactly.")
    available = set(all_actions)
    blocks = defaultdict(list)
    for world in worlds:
        if not set(world["successful"]).issubset(available):
            raise ValueError("Successful actions must belong to the declared action menu.")
        blocks[canonical(partition[world["id"]])].append(world)
    decisions, failures = {}, []
    preserves_options = True
    for label, members in sorted(blocks.items()):
        choices = available.copy()
        for world in members:
            choices &= set(world["successful"])
        options = {tuple(sorted(w["successful"])) for w in members}
        preserves_options &= len(options) == 1
        if choices:
            decisions[label] = sorted(choices)
        else:
            failures.append({"class": label, "worlds": [w["id"] for w in members]})
    return {
        "one_step_success": not failures,
        "preserves_successful_options": preserves_options,
        "uniform_choices": decisions,
        "failures": failures,
        "classes": len(blocks),
    }


# Independent pair-elimination and exhaustive one-step policy references.


def relation_oracle(model, partition, max_pairs=2_000_000):
    rows = {r["id"]: r for r in model["states"]}
    if model.get("complete") is not True or set(rows) != set(partition):
        raise ValueError("Reference requires complete matching domains.")

    def same(x, y):
        return json.dumps(x, sort_keys=True, allow_nan=False) == json.dumps(
            y, sort_keys=True, allow_nan=False
        )

    groups = {}
    for sid in rows:
        groups.setdefault(json.dumps(partition[sid], sort_keys=True), []).append(sid)
    if sum(len(group) ** 2 for group in groups.values()) > max_pairs:
        raise ValueError("Independent reference candidate-pair bound exceeded.")
    pairs = {
        (p, q)
        for group in groups.values()
        for p in group
        for q in group
        if same(rows[p]["observation"], rows[q]["observation"])
    }
    rounds = 0
    while True:
        rejected = set()
        for p, q in pairs:
            for left, right in ((p, q), (q, p)):
                for edge in rows[left]["edges"]:
                    if not any(
                        edge["action"] == other["action"] and (edge["to"], other["to"]) in pairs
                        for other in rows[right]["edges"]
                    ):
                        rejected.add((p, q))
                        break
                if (p, q) in rejected:
                    break
        rounds += 1
        if not rejected:
            return pairs, rounds
        pairs -= rejected


def policy_oracle(worlds, partition, actions):
    labels = sorted(set(partition.values()), key=str)
    winning = []
    for choices in product(actions, repeat=len(labels)):
        mapping = dict(zip(labels, choices))
        if all(mapping[partition[w["id"]]] in w["successful"] for w in worlds):
            winning.append(mapping)
    return winning


def partitions(items):
    """All set partitions as canonical restricted-growth maps, small n only."""
    if not items or len(items) > 5:
        raise ValueError("Exhaustive root partition oracle is bounded to 1..5 states.")

    def visit(labels):
        if len(labels) == len(items):
            yield dict(zip(items, labels))
        else:
            for label in range(max(labels) + 2):
                yield from visit(labels + [label])

    yield from visit([0])


# Fictional handover authored after the original diagnostic was frozen.


def build(delegate=False, review=False):
    # A synthetic digital handover. Both packages can undergo a fresh inspection.
    # One already carries a certificate. Delegation exposes that distinction later.
    def state(sid, phase, edges):
        return {
            "id": sid,
            "observation": {"phase": phase, "complete": phase == "accepted"},
            "edges": [{"action": a, "to": t} for a, t in edges],
        }

    rows = [
        state("installed-with-certificate", "installed", [("inspect", "checked")]),
        state("installed-without-certificate", "installed", [("inspect", "checked")]),
        state("checked", "checked", [("sign-off", "accepted")]),
        state("accepted", "accepted", []),
    ]
    if delegate:
        rows[0]["edges"].append({"action": "delegate", "to": "delegated-with-certificate"})
        rows[1]["edges"].append({"action": "delegate", "to": "delegated-without-certificate"})
        rows += [
            state("delegated-with-certificate", "delegated", [("accept", "accepted")]),
            state("delegated-without-certificate", "delegated", [("request-proof", "checked")]),
        ]
    if review:
        for row in rows:
            row["edges"].append({"action": "review-record", "to": row["id"]})
    return {
        "id": "fresh-handover"
        + ("-delegated" if delegate else "-baseline")
        + ("-review" if review else ""),
        "complete": True,
        "initial": [rows[0]["id"], rows[1]["id"]],
        "states": rows,
    }, {r["id"]: r["observation"]["phase"] for r in rows}


def checked_case(key, title, model, partition, notes):
    initial = diagnose(model, partition)
    if initial["status"] == "unresolved":
        return {"id": key, "title": title, "notes": notes, "initial": initial}
    repair = refine(model, partition)
    try:
        pairs, rounds = relation_oracle(model, partition)
    except ValueError as exc:
        return {
            "id": key,
            "title": title,
            "notes": notes,
            "initial": {
                "status": "unresolved",
                "reason": "Independent verification unavailable: " + str(exc),
            },
            "candidate_status": initial["status"],
        }
    ids = list(partition)
    candidate_pairs = {
        (a, b) for a in ids for b in ids if repair["partition"][a] == repair["partition"][b]
    }
    assert pairs == candidate_pairs, f"Candidate/reference disagreement: {key}"
    assert diagnose(model, repair["partition"])["status"] == "sufficient"
    original_pairs = {
        (a, b) for a in ids for b in ids if canonical(partition[a]) == canonical(partition[b])
    }
    assert (initial["status"] == "sufficient") == (pairs == original_pairs)
    full = diagnose(model, {s: s for s in ids})
    assert full["status"] == "sufficient"
    witness = initial.get("witness")
    if witness:
        states = {s["id"]: s for s in model["states"]}
        witness["left_record"] = states[witness["left"]]
        witness["right_record"] = states[witness["right"]]
    return {
        "id": key,
        "title": title,
        "notes": notes,
        "initial": initial,
        "states": len(ids),
        "edges": sum(len(r["edges"]) for r in model["states"]),
        "summary_classes": len({canonical(value) for value in partition.values()}),
        "repair_classes": repair["classes"],
        "repair_rounds": repair["rounds"],
        "repair_partition": repair["partition"],
        "full_model_classes": full["classes"],
        "independent_pair_rounds": rounds,
        "independent_agreement": True,
    }


def read_bytes(relative_path, online):
    if online:
        with urlopen(urljoin(PUBLIC_ROOT, relative_path), timeout=30) as response:
            return response.read()
    return (ROOT / relative_path).read_bytes()


def read_checked_input(relative_path, expected_hash, online):
    data = read_bytes(relative_path, online)
    if hashlib.sha256(data).hexdigest() != expected_hash:
        raise ValueError(f"Unexpected input bytes: {relative_path}")
    return json.loads(data)


def run(online=False):
    rotunda, gimmer, knowing = [read_checked_input(path, digest, online) for path, digest in INPUTS]
    records = []
    for context in rotunda["contexts"]:
        model = {
            "complete": context["complete"],
            "initial": [context["initial"]],
            "states": context["states"],
        }
        for kind in ["oldClosedConservativeExtension", "openInterface"]:
            title = {
                "one-hoist": "One hoist",
                "two-hoists": "Two hoists",
                "closed-B": "Front B closed",
            }[context["id"]]
            summary = (
                "old summary reused"
                if kind == "oldClosedConservativeExtension"
                else "open component summary"
            )
            record = checked_case(
                "120-" + context["id"] + "-" + kind,
                "Rotunda: " + title + " / " + summary,
                model,
                context["partitions"][kind],
                rotunda["semantics"] + " " + rotunda["partitionExtension"],
            )
            if "witness" in record["initial"]:
                for side in ["left", "right"]:
                    witness = record["initial"]["witness"]
                    witness[side + "_record"]["concrete_detail"] = rotunda["concreteStates"][
                        witness[side]
                    ]
            records.append(record)
        if context["id"] == "one-hoist":
            review = copy.deepcopy(model)
            for row in review["states"]:
                row["edges"].append({"action": "review-record", "to": row["id"]})
            records.append(
                checked_case(
                    "120-harmless-review",
                    "Rotunda: harmless review option",
                    review,
                    context["partitions"]["oldClosedConservativeExtension"],
                    "Uniform self-loop adds an option without revealing a hidden distinction; no progress guarantee claimed.",
                )
            )
    guards = []
    for case in gimmer["cases"]:
        rows = [
            {
                "id": s["id"],
                "observation": {**s["observation"], "complete": s["terminal"]},
                "edges": [],
            }
            for s in case["states"]
        ]
        lookup = {r["id"]: r for r in rows}
        for edge in case["transitions"]:
            lookup[edge["from"]]["edges"].append({"action": edge["action"], "to": edge["to"]})
        model = {"complete": case["complete"], "initial": [case["initial"]], "states": rows}
        guards.append(json.dumps(case["receiverGuard"], sort_keys=True))
        for name in ["completedIdentity", "boundaryOnlyDefective"]:
            summary = (
                "completed-work record" if name == "completedIdentity" else "boundary counts only"
            )
            records.append(
                checked_case(
                    "155-" + case["id"] + "-" + name,
                    "Gimmer: initial support "
                    + str(case["context"]["initialSupport"])
                    + " / "
                    + summary,
                    model,
                    case["summaries"][name],
                    gimmer["semantics"],
                )
            )
    assert len(set(guards)) == 1, "The receiver representation changed across contexts."
    for delegate, review in [(False, False), (True, False), (False, True)]:
        model, p = build(delegate, review)
        records.append(
            checked_case(
                model["id"],
                "Digital handover: "
                + ("delegated" if delegate else "inspection")
                + (" plus review" if review else ""),
                model,
                p,
                "Fresh synthetic case authored after freeze7c5e82f; not blinded. Old phase summary is explicitly extended with one shared delegated phase. All outcomes deterministic. The certificate distinction affects what the delegate can subsequently do.",
            )
        )
    model, p = build()
    model["complete"] = False
    records.append(
        checked_case(
            "incomplete-control",
            "Incomplete enumeration",
            model,
            p,
            "Incomplete evidence must produce unresolved, even where visible rows appear stable.",
        )
    )
    policies = []
    for case in knowing["cases"]:
        worlds = [{"id": w["id"], "successful": w["allowed"]} for w in case["worlds"]]
        actions = sorted({a for w in worlds for a in w["successful"]})
        checks = []
        for partition in case["partitions"]:
            p = {sid: i for i, cell in enumerate(partition["cells"]) for sid in cell}
            result = one_step_policy(worlds, p, actions)
            enumeration = policy_oracle(worlds, p, actions)
            assert result["one_step_success"] == bool(enumeration) == partition["chooseOne"]
            assert result["preserves_successful_options"] == partition["preserveAll"]
            assert len(enumeration) == partition["policyCount"]
            checks.append(result)
        policies.append(
            {
                "id": case["scenario"]["id"],
                "title": case["scenario"]["title"],
                "worlds": len(worlds),
                "partitions_checked": len(checks),
                "fewest_outcomes_for_one_action": min(
                    c["classes"] for c in checks if c["one_step_success"]
                ),
                "fewest_outcomes_for_all_successful_options": min(
                    c["classes"] for c in checks if c["preserves_successful_options"]
                ),
                "independent_policy_agreement": True,
            }
        )
    return {
        "schema": "pw355-essai01-v1",
        "diagnostic_freeze": "7c5e82f",
        "transition_cases": records,
        "policy_controls": policies,
        "receiver_guard_unchanged": True,
        "limits": "Supplied finite models only. Strong labelled-step preservation; separate one-step policy control. No learned missing schema, real-project validation or runtime saving measured.",
    }


def serialise(value):
    return (json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode("utf-8")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--online",
        action="store_true",
        help="Fetch the three checksum-pinned public JSON inputs from the essai.",
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Compare recomputed evidence and the reader fixture to the published edition.",
    )
    args = parser.parse_args()
    if not __debug__:
        parser.error("Use standard Python without -O so the reference checks execute.")
    result = run(args.online)
    result_data = serialise(result)
    if hashlib.sha256(result_data).hexdigest() != RESULT_SHA256:
        raise ValueError("Recomputed evidence differs from the retained first-essai result.")
    handover = {"baseline": build()[0], "delegated": build(delegate=True)[0]}
    if args.check:
        if result_data != read_bytes("results.json", args.online):
            raise ValueError("Saved results differ from the replay.")
        if serialise(handover) != read_bytes("handover.json", args.online):
            raise ValueError("Displayed handover model differs from the replay.")
    for case in result["transition_cases"]:
        print(
            case["id"],
            case["initial"]["status"],
            case.get("summary_classes"),
            case.get("repair_classes"),
        )
    policies = sum(case["partitions_checked"] for case in result["policy_controls"])
    print(f"Policy partitions independently checked: {policies}")
    print("First-essai results match the historical SHA-256.")


if __name__ == "__main__":
    main()
