#!/usr/bin/env python3
"""Offline Agent Key v4.3 oracle over already verified, synthetic Bitcoin facts."""

import argparse
from collections import Counter
from dataclasses import dataclass, replace
from hashlib import sha256
import json
from pathlib import Path
import random
import sys

MAGIC = b"AIBR"
MAX128 = (1 << 128) - 1
ZERO32 = bytes(32).hex()
OPERATIONS = {3: "delegate", 4: "revoke", 5: "transfer_for", 6: "revoke_all"}
FIXED_PREFIX = {"delegate": 34, "revoke": 34, "transfer_for": 35, "revoke_all": 2}
ASSET_FIELDS = ("assetId", "name", "network", "totalSupply", "deployTxid",
                "ownerOutputIndex", "locator")
CHANGED_TABLES = ("balances", "grants", "grantGroups", "ownerEpochs")
SIX_KEYS = ("grantId", "debitedAccount", "signingAccount", "assetId", "operation", "cleanup")
DEFAULT_FIXTURES = Path(__file__).resolve().parents[2] / "vectors" / "agent-key" / "expectations.json"
RULES_SHA256 = "c015a09ca5972c0d4acbb49e9af6fb7a9ca6e4ec67e304f965dbb9ae7b366e9f"
UNKNOWN = "UNKNOWN"


class Reject(Exception):
    """First transaction-level reason. No consensus state is published for it."""


class StopBlock(Exception):
    def __init__(self, status, reason, input_index=None):
        self.status = status
        self.reason = reason
        self.input_index = input_index


def tagged(label, message):
    domain = sha256(label.encode("utf-8")).digest()
    return sha256(domain + domain + message).digest()


def raw32(text):
    raw = bytes.fromhex(text)
    if len(raw) != 32:
        raise ValueError("a synthetic identifier or mark must be 32 bytes")
    return raw


def formula(kind, network, info):
    n = bytes([network])
    owner = raw32(info["owner"])
    if kind == "grantId":
        return "AIBRC/grant/v1", n + raw32(info["txid"]) + b"\0" + owner + raw32(info["assetId"])
    if kind == "newE":
        return "AIBRC/owner-epoch/v1", n + owner + raw32(info["blockHash"]) + raw32(info["txid"])
    group = n + owner + raw32(info["agent"]) + raw32(info["assetId"])
    if kind == "newG":
        return "AIBRC/group-revision/v1", group + raw32(info["blockHash"]) + raw32(info["txid"])
    if kind != "expectedContext":
        raise ValueError(f"unknown formula {kind!r}")
    remaining = int(info["currentRemaining"]).to_bytes(16, "big")
    state = raw32(info["currentE"]) + raw32(info["currentG"]) + remaining
    return "AIBRC/expected-context/v1", group + state


def formula_result(kind, network, info):
    domain, message = formula(kind, network, info)
    digest = tagged(domain, message).hex()
    return {"messageHex": message.hex(), "digestHex": digest,
            "valueHex": digest[:22] if kind == "expectedContext" else digest}


def derive(kind, network, **parts):
    return formula_result(kind, network, parts)["valueHex"]


def leb(value, width):
    if not 0 <= value < 1 << width:
        raise ValueError(f"value outside u{width}")
    encoded = bytearray()
    while value > 127:
        encoded.append((value & 127) | 128)
        value >>= 7
    encoded.append(value)
    return bytes(encoded)


def encode(network, decoded):
    op = decoded["operation"]
    head = int(decoded["authInput"]).to_bytes(2, "big")
    if op == "delegate":
        commitment = bytes.fromhex(decoded["expectedContext"])
        if len(commitment) != 11:
            raise ValueError("delegate requires an 11-byte expectedContext")
        body = b"".join((head, raw32(decoded["assetId"]), leb(decoded["agentOutput"], 16),
                         leb(int(decoded["amount"]), 128), decoded["expiry"].to_bytes(4, "big"),
                         commitment))
    elif op == "revoke":
        body = head + raw32(decoded["grantId"])
    elif op == "transfer_for":
        items = decoded["items"]
        if not 1 <= len(items) <= 25:
            raise ValueError("transfer_for requires 1–25 allocations")
        body = head + bytes([len(items)]) + raw32(decoded["grantId"])
        body += b"".join(leb(vout, 16) + leb(int(amount), 128) for vout, amount in items)
    elif op == "revoke_all":
        body = head
    else:
        raise ValueError(f"unknown operation {op!r}")
    if len(body) + 9 > 480:
        raise ValueError("payload exceeds 480 bytes")
    opcode = next(code for code, name in OPERATIONS.items() if name == op)
    return MAGIC + bytes((2, network, opcode)) + len(body).to_bytes(2, "big") + body


class Cursor:
    def __init__(self, body, offset):
        self.body = body
        self.offset = offset

    def read(self, size):
        end = self.offset + size
        if end > len(self.body):
            raise Reject("TRUNCATED_PAYLOAD")
        value = self.body[self.offset:end]
        self.offset = end
        return value

    def read_leb(self, width, overflow):
        value = 0
        shift = 0
        while True:
            digit = self.read(1)[0]
            low = digit & 127
            if shift >= 128 and low:
                raise Reject(overflow)
            value |= low << shift
            if digit < 128:
                if shift and not low:
                    raise Reject("NON_CANONICAL_INTEGER")
                if value >= 1 << width:
                    raise Reject(overflow)
                return value
            shift += 7
            if shift > 133:
                raise Reject(overflow)

    def require_end(self):
        if self.offset != len(self.body):
            raise Reject("LENGTH_MISMATCH")


def header(payload, network):
    if payload[:4] != MAGIC:
        raise Reject("NOT_AIBRC")
    if len(payload) < 9:
        raise Reject("TRUNCATED_PAYLOAD")
    if len(payload) > 480:
        raise Reject("PAYLOAD_TOO_LARGE")
    if payload[5] != network:
        raise Reject("UNKNOWN_NETWORK")


def allocation_items(cursor, count):
    if count == 0:
        raise Reject("EMPTY_ALLOCATIONS")
    if count > 25:
        raise Reject("TOO_MANY_ALLOCATIONS")
    return [
        [cursor.read_leb(16, "RECEIVER_OUTPUT_INDEX_OUT_OF_RANGE"),
         str(cursor.read_leb(128, "U128_OVERFLOW"))]
        for _ in range(count)
    ]


def decode_v2(payload):
    op = OPERATIONS.get(payload[6])
    if op is None:
        raise Reject("UNKNOWN_OPCODE")
    body = payload[9:]
    if len(body) != int.from_bytes(payload[7:9], "big"):
        raise Reject("LENGTH_MISMATCH")
    prefix = FIXED_PREFIX[op]
    if len(body) < prefix:
        raise Reject("TRUNCATED_PAYLOAD")
    decoded = {"operation": op, "authInput": int.from_bytes(body[:2], "big")}
    cursor = Cursor(body, prefix)
    if op == "delegate":
        decoded["assetId"] = body[2:34].hex()
        decoded["agentOutput"] = cursor.read_leb(16, "RECEIVER_OUTPUT_INDEX_OUT_OF_RANGE")
        decoded["amount"] = str(cursor.read_leb(128, "U128_OVERFLOW"))
        decoded["expiry"] = int.from_bytes(cursor.read(4), "big")
        decoded["expectedContext"] = cursor.read(11).hex()
    elif op == "revoke":
        decoded["grantId"] = body[2:34].hex()
    elif op == "transfer_for":
        decoded["grantId"] = body[3:35].hex()
        decoded["items"] = allocation_items(cursor, body[2])
    cursor.require_end()
    return decoded


def decode_v1_transfer(payload):
    """V0.25 §5. This reference consumes already-deployed assets."""
    if payload[6] == 1:
        raise ValueError("V1 Deploy is outside the reference; supply its verified pre-state")
    if payload[6] != 2:
        raise Reject("UNKNOWN_OPCODE")
    body = payload[9:]
    if len(body) != int.from_bytes(payload[7:9], "big"):
        raise Reject("LENGTH_MISMATCH")
    cursor = Cursor(body, 0)
    auth = int.from_bytes(cursor.read(2), "big")
    count = cursor.read(1)[0]
    deployment = int.from_bytes(cursor.read(4), "big")
    tx_index = int.from_bytes(cursor.read(2), "big")
    items = allocation_items(cursor, count)
    cursor.require_end()
    return auth, f"{deployment}:{tx_index}", items


@dataclass(frozen=True)
class Marker:
    payload: bytes
    error: str | None = None


def extract(script):
    """Read only the first OP_RETURN push (v0.25 Hardening Addendum §3)."""
    if len(script) < 2 or script[0] != 0x6a:
        return None
    opcode = script[1]
    if 1 <= opcode <= 75:
        count, start, minimum = opcode, 2, 1
    elif opcode in (76, 77, 78):
        size_bytes = (1, 2, 4)[opcode - 76]
        start = 2 + size_bytes
        if len(script) < start:
            return None
        count = int.from_bytes(script[2:start], "little")
        minimum = (76, 256, 65536)[opcode - 76]
    else:
        return None
    pushed = script[start:start + count]
    if not pushed.startswith(MAGIC):
        return None
    if count < minimum:
        return Marker(pushed, "NON_MINIMAL_PUSH")
    if len(pushed) != count:
        return Marker(pushed, "PUSH_LENGTH_MISMATCH")
    if start + count != len(script):
        return Marker(pushed, "TRAILING_SCRIPT_OPERATION")
    return Marker(pushed)


def markers(outputs):
    return [mark for output in outputs
            if (mark := extract(bytes.fromhex(output["scriptPubKeyHex"]))) is not None]


def push(payload):
    count = len(payload)
    if count <= 75:
        prefix = bytes([count])
    elif count <= 255:
        prefix = bytes([76, count])
    else:
        prefix = bytes([77]) + count.to_bytes(2, "little")
    return (b"\x6a" + prefix + payload).hex()


def script_type(script):
    if len(script) == 34 and script[:2] == b"\x51\x20":
        return "P2TR_KEY_PATH"
    if len(script) == 22 and script[:2] == b"\x00\x14":
        return "P2WPKH"
    raise Reject("UNSUPPORTED_SCRIPT")


def account(script):
    return tagged("AIBRC/account/v1", script).hex()


def authorization(inputs, index):
    if index >= len(inputs):
        raise Reject("INVALID_AUTH_INPUT")
    tx_input = inputs[index]
    script = bytes.fromhex(tx_input["prevoutScriptPubKeyHex"] or "")
    kind = script_type(script)
    allowed = (0, 1) if kind == "P2TR_KEY_PATH" else (1,)
    if tx_input["witnessType"] != kind or tx_input["sighashType"] not in allowed:
        raise Reject("UNSUPPORTED_SIGHASH")
    return script, account(script)


def output_account(transaction, index, error):
    outputs = transaction["outputs"]
    if index >= len(outputs):
        raise Reject(error)
    script = bytes.fromhex(outputs[index]["scriptPubKeyHex"])
    if script.startswith(b"\x6a"):
        raise Reject(error)
    script_type(script)
    return account(script)


@dataclass(frozen=True)
class Grant:
    identifier: str
    owner: str
    agent: str
    asset: str
    cap: str
    remaining: str
    height: int
    expiry: int
    epoch: str

    @property
    def group(self):
        return self.owner, self.agent, self.asset

    def row(self):
        return [self.identifier, *self.group, self.cap, self.remaining,
                self.height, self.expiry, self.epoch]


class State:
    """State built from a supplied, already validated synthetic V1/V2 snapshot."""

    def __init__(self, snapshot):
        self.assets = {a["assetId"]: {field: a[field] for field in ASSET_FIELDS}
                       for a in snapshot["assets"]}
        self.names = dict(snapshot["names"])
        self.locators = dict(snapshot["locators"])
        self.balances = {key: int(amount) for key, amount in snapshot["balances"]}
        self.grants = {row[0]: Grant(*row) for row in snapshot.get("grants", [])}
        self.groups = {tuple(row[:3]): row[3] for row in snapshot.get("grantGroups", [])}
        self.epochs = dict(snapshot.get("ownerEpochs", []))

    def snapshot(self):
        result = {
            "assets": [asset for _, asset in sorted(self.assets.items())],
            "names": [list(row) for row in sorted(self.names.items(), key=lambda row: row[0].encode())],
            "locators": [[key, self.locators[key]] for key in sorted(
                self.locators, key=lambda locator: tuple(map(int, locator.split(":"))))],
            "balances": [[key, str(value)] for key, value in sorted(self.balances.items()) if value > 0],
        }
        if self.grants:
            result["grants"] = [g.row() for _, g in sorted(self.grants.items())]
        if self.groups:
            result["grantGroups"] = [[*group, g] for group, g in sorted(self.groups.items())]
        if self.epochs:
            result["ownerEpochs"] = [[key, e] for key, e in sorted(self.epochs.items())]
        return result

    def epoch(self, owner):
        return self.epochs.get(owner, ZERO32)

    def grant_for_group(self, group):
        return next((grant for grant in self.grants.values() if grant.group == group), None)

    def balance(self, asset, identity):
        return self.balances.get(f"{asset}:{identity}", 0)

    def adjust(self, asset, identity, delta):
        key = f"{asset}:{identity}"
        updated = self.balances.get(key, 0) + delta
        if not 0 <= updated <= MAX128:
            raise ValueError("invalid synthetic state: balance outside u128")
        if updated:
            self.balances[key] = updated
        else:
            self.balances.pop(key, None)


def compact(snapshot):
    return json.dumps(snapshot, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def canonical_view(snapshot):
    payload = compact(snapshot)
    return {"canonicalHex": payload.hex(), "bytes": len(payload), "sha256": sha256(payload).hexdigest()}


def changes(old, new):
    result = {}
    for field in CHANGED_TABLES:
        def index(rows):
            return {":".join(row[:3]) if field == "grantGroups" else row[0]: row for row in rows}

        before, after = index(old.get(field, [])), index(new.get(field, []))
        result[field] = [[key, before.get(key), after.get(key)]
                         for key in sorted(set(before) | set(after))
                         if before.get(key) != after.get(key)]
    return result


def project_prefix(payload):
    op = OPERATIONS.get(payload[6])
    record = dict.fromkeys(SIX_KEYS)
    record.update(operation=op, cleanup=False)
    if op is None or len(payload) - 9 < FIXED_PREFIX[op]:
        return record
    if op == "delegate":
        record["assetId"] = payload[11:43].hex()
    elif op == "transfer_for":
        record["grantId"] = payload[12:44].hex()
    elif op == "revoke":
        record["grantId"] = payload[11:43].hex()
    return record


def apply_delegate(state, tx, block, network, decoded, result, owner):
    h = block["height"]
    asset = decoded["assetId"]
    if asset not in state.assets:
        raise Reject("UNKNOWN_ASSET")
    agent = output_account(tx, decoded["agentOutput"], "INVALID_AGENT_OUTPUT")
    if agent == owner:
        raise Reject("SELF_GRANT")
    amount, expiry = decoded["amount"], decoded["expiry"]
    if amount == "0":
        raise Reject("ZERO_AMOUNT")
    if state.balance(asset, owner) == 0:
        raise Reject("ZERO_OWNER_BALANCE")
    if expiry < h + 1:
        raise Reject("GRANT_EXPIRY_TOO_EARLY")
    group = owner, agent, asset
    old = state.grant_for_group(group)
    epoch = state.epoch(owner)
    remaining = old.remaining if old is not None and old.epoch == epoch else "0"
    args = dict(owner=owner, agent=agent, assetId=asset)
    commitment = derive("expectedContext", network, **args, currentE=epoch,
                        currentG=state.groups.get(group, ZERO32), currentRemaining=remaining)
    if commitment != decoded["expectedContext"]:
        raise Reject("GRANT_CONTEXT_MISMATCH")
    identifier = derive("grantId", network, **args, txid=tx["txid"])
    revision = derive("newG", network, **args, blockHash=block["hash"], txid=tx["txid"])
    if old is not None:
        del state.grants[old.identifier]
    state.groups[group] = revision
    state.grants[identifier] = Grant(identifier, *group, amount, amount, h, expiry, epoch)
    result["grantId"] = identifier


def indexed_grant(state, identifier):
    grant = state.grants.get(identifier)
    if grant is None:
        raise Reject("UNKNOWN_GRANT")
    return grant


def apply_revoke(state, tx, block, network, decoded, result, signer):
    grant = indexed_grant(state, decoded["grantId"])
    if signer != grant.owner:
        raise Reject("NOT_GRANT_OWNER")
    cleanup = grant.epoch != state.epoch(grant.owner)
    if not cleanup:
        state.groups[grant.group] = derive(
            "newG", network, owner=grant.owner, agent=grant.agent, assetId=grant.asset,
            blockHash=block["hash"], txid=tx["txid"],
        )
    del state.grants[grant.identifier]
    result.update(debitedAccount=grant.owner, assetId=grant.asset, cleanup=cleanup)


def payment_deltas(tx, items):
    total, allocations, delta = 0, [], Counter()
    for vout, encoded_amount in items:
        amount = int(encoded_amount)
        if amount == 0:
            raise Reject("ZERO_AMOUNT")
        recipient = output_account(tx, vout, "INVALID_RECEIVER_OUTPUT")
        total += amount
        if total > MAX128:
            raise Reject("U128_OVERFLOW")
        allocations.append([vout, recipient, encoded_amount])
        delta[recipient] += amount
    return total, allocations, delta


def commit_deltas(state, asset, owner, total, delta):
    delta[owner] -= total
    for identity, amount in delta.items():
        state.adjust(asset, identity, amount)


def apply_v1_transfer(state, tx, payload, result):
    auth, locator, items = decode_v1_transfer(payload)
    _, sender = authorization(tx["inputs"], auth)
    asset = state.locators.get(locator)
    if asset is None:
        raise Reject("UNKNOWN_ASSET")
    total, allocations, delta = payment_deltas(tx, items)
    if state.balance(asset, sender) < total:
        raise Reject("INSUFFICIENT_BALANCE")
    commit_deltas(state, asset, sender, total, delta)
    result.update(assetId=asset, allocations=allocations)


def apply_payment(state, tx, block, decoded, result, signer):
    grant = indexed_grant(state, decoded["grantId"])
    if signer != grant.agent:
        raise Reject("NOT_GRANT_AGENT")
    result.update(debitedAccount=grant.owner, assetId=grant.asset)
    if grant.epoch != state.epoch(grant.owner):
        raise Reject("GRANT_EPOCH_MISMATCH")
    height = block["height"]
    if height < grant.height + 1:
        raise Reject("GRANT_NOT_ACTIVE")
    if height > grant.expiry:
        raise Reject("GRANT_EXPIRED")
    total, allocations, delta = payment_deltas(tx, decoded["items"])
    remaining = int(grant.remaining) - total
    if remaining < 0:
        raise Reject("ALLOWANCE_EXCEEDED")
    if state.balance(grant.asset, grant.owner) < total:
        raise Reject("INSUFFICIENT_BALANCE")

    commit_deltas(state, grant.asset, grant.owner, total, delta)
    if remaining:
        state.grants[grant.identifier] = replace(grant, remaining=str(remaining))
    else:
        del state.grants[grant.identifier]
    result.update(grossSpent=str(total), allocations=allocations)


def enabled_v2(payload, block, settings):
    version = payload[4]
    height = block["height"]
    if version == 2:
        k = settings["activationHeight"]
        if k is None or height < k:
            raise Reject("UNKNOWN_VERSION")
        return True
    if version == 1:
        return False
    activation = settings.get("futureActivationHeights", {}).get(str(version))
    if activation is not None and height >= activation:
        raise StopBlock("NEEDS_UPGRADE", "UNKNOWN_VERSION")
    raise Reject("UNKNOWN_VERSION")


def apply_v2(state, tx, block, network, payload, result):
    result.update(project_prefix(payload))
    decoded = decode_v2(payload)
    op = decoded["operation"]
    # 1.1 and 1.2. Retain only the roles verified before the reject point.
    script, signer = authorization(tx["inputs"], decoded["authInput"])
    result["signingAccount"] = signer
    if op in ("delegate", "revoke_all"):
        result["debitedAccount"] = signer
    if op != "transfer_for" and any(
        bytes.fromhex(tx_in["prevoutScriptPubKeyHex"] or "") != script for tx_in in tx["inputs"]
    ):
        raise Reject("MANAGEMENT_INPUT_SCRIPT_MISMATCH")
    if op == "delegate":
        apply_delegate(state, tx, block, network, decoded, result, signer)
    elif op == "revoke":
        apply_revoke(state, tx, block, network, decoded, result, signer)
    elif op == "revoke_all":
        state.epochs[signer] = derive("newE", network, owner=signer,
                                      blockHash=block["hash"], txid=tx["txid"])
    else:
        apply_payment(state, tx, block, decoded, result, signer)


def execute(state, tx, block, settings):
    before = state.snapshot()
    result = {"txIndex": tx["txIndex"], "txid": tx["txid"], "status": "NO_OP",
              "reason": "VALID", "grossSpent": "0", "allocations": []}
    try:
        found = markers(tx["outputs"])
        # 0.0. A recognizable malformed-only transaction needs no prevouts.
        if any(mark.error is None for mark in found):
            for index, tx_in in enumerate(tx["inputs"]):
                if not tx_in.get("coinbase") and tx_in["prevoutScriptPubKeyHex"] is None:
                    raise StopBlock("WAIT", "MISSING_PREVOUT", index)
        # 0.1 through 0.4. Select projection shape only after 0.2 has passed.
        if len(found) > 1:
            raise Reject("DUPLICATE_STATE_INSTRUCTION")
        if not found:
            raise Reject("NOT_AIBRC")
        mark = found[0]
        if mark.error is not None:
            raise Reject(mark.error)
        payload = mark.payload
        network = settings["network"]
        header(payload, network)
        if enabled_v2(payload, block, settings):
            apply_v2(state, tx, block, network, payload, result)
        else:
            apply_v1_transfer(state, tx, payload, result)
        result["status"] = "APPLIED"
    except Reject as rejection:
        result["reason"] = str(rejection)

    after = state.snapshot()
    result.update(changes=changes(before, after), afterState=after)
    return result


class Replay:
    """Stage one whole block at a time and retain its pre-state for undo."""

    def __init__(self, settings):
        self.settings = settings
        self.state = State(settings["preState"]).snapshot()
        self.tip = settings.get("startingTip")
        self.history = []
        self.undo = []

    def rewind_to(self, block_count):
        while len(self.history) > block_count:
            self.state, self.tip = self.undo.pop()
            self.history.pop()

    def append(self, block):
        height, block_hash = block["height"], block.get("hash")
        if self.tip is not None and height != self.tip["height"] + 1:
            raise ValueError("synthetic blocks must be consecutive")
        location = {"height": height, "hash": block_hash}
        if block_hash is None or "activationHeight" not in self.settings or block.get("rulesMissing"):
            return "WAIT", {**location, "reason": "MISSING_BLOCK_OR_RULE_DATA"}
        raw32(block_hash)
        provisional = State(self.state)
        outcomes = []
        ordered = sorted(block["transactions"], key=lambda tx: tx["txIndex"])
        indexes = [tx["txIndex"] for tx in ordered]
        if len(set(indexes)) != len(indexes):
            raise ValueError("synthetic txIndex values must be unique")
        for tx in ordered:
            if "preState" in tx:
                difference = first_difference(tx["preState"], provisional.snapshot())
                if difference:
                    raise ValueError(f"recorded pre-state differs at {height}/{tx['txIndex']}: {difference}")
            try:
                outcomes.append(execute(provisional, tx, block, self.settings))
            except StopBlock as stop:
                diagnostic = {**location, "txIndex": tx["txIndex"], "reason": stop.reason}
                if stop.input_index is not None:
                    diagnostic["inputIndex"] = stop.input_index
                return stop.status, diagnostic
        self.undo.append((self.state, self.tip))
        self.state, self.tip = provisional.snapshot(), location
        self.history.append({**location, "outcomes": outcomes, **canonical_view(self.state)})
        return None

    def follow(self, blocks):
        committed = []
        for block in blocks:
            stopped = self.append(block)
            if stopped is not None:
                status, where = stopped
                return {"status": status, "tip": self.tip, "blocks": committed, "blocked": where}
            committed.append(self.history[-1])
        return {"status": "OK", "tip": self.tip, "blocks": committed}


def grant_rows(snapshot):
    return {grant[0]: grant for grant in snapshot.get("grants", [])}


def live_grant_state(grant, snapshot, height):
    if grant is None:
        return UNKNOWN
    if grant[8] != dict(snapshot.get("ownerEpochs", [])).get(grant[1], ZERO32):
        return "OLD_EPOCH"
    if height is None:
        return UNKNOWN
    if height < grant[6] + 1:
        return "IMMATURE"
    if height > grant[7]:
        return "EXPIRED"
    return "ACTIVE"


def ended_grant_state(outcome):
    operation = outcome["operation"]
    if operation == "transfer_for":
        return "EXHAUSTED"
    if operation == "delegate":
        return "REPLACED"
    if operation == "revoke":
        return "CLEANED_OLD_EPOCH" if outcome["cleanup"] else "REVOKED"
    raise ValueError(f"unexpected grant deletion by {operation}")


def coordinate(block, tx):
    return block["height"], block["hash"], tx["txIndex"], tx["txid"]


def position(coord):
    return dict(zip(("height", "blockHash", "txIndex", "txid"), coord, strict=True))


def remaining(grant, status):
    if status == "EXHAUSTED":
        return "0"
    return grant[5] if grant is not None else UNKNOWN


def transaction_query(coord, outcome=None, before=None):
    if outcome is None:
        return {
            "position": position(coord), "status": UNKNOWN, "operation": UNKNOWN,
            "grantId": UNKNOWN, "assetId": UNKNOWN, "debitedAccount": UNKNOWN,
            "signingAccount": UNKNOWN, "grantState": UNKNOWN, "remainingBefore": UNKNOWN,
            "remainingAfter": UNKNOWN, "actualSpent": UNKNOWN, "failureReason": UNKNOWN,
        }
    grant_id = outcome.get("grantId")
    after = outcome["afterState"]
    applied = outcome["status"] == "APPLIED"
    # A raw prefix can index a failed reference. It cannot establish its economics.
    has_roles = grant_id is not None and outcome.get("debitedAccount") is not None
    prior = grant_rows(before).get(grant_id) if has_roles else None
    current = grant_rows(after).get(grant_id) if has_roles else None
    stage = (ended_grant_state(outcome) if applied and prior is not None and current is None
             else live_grant_state(current, after, coord[0]))
    asset = outcome.get("assetId") if applied or has_roles else None
    return {
        "position": position(coord), "status": outcome["status"],
        "operation": outcome.get("operation") or UNKNOWN, "grantId": grant_id or UNKNOWN,
        "assetId": asset or UNKNOWN, "debitedAccount": outcome.get("debitedAccount") or UNKNOWN,
        "signingAccount": outcome.get("signingAccount") or UNKNOWN, "grantState": stage,
        "remainingBefore": prior[5] if prior is not None else UNKNOWN,
        "remainingAfter": remaining(current, stage), "actualSpent": outcome["grossSpent"],
        "failureReason": None if applied else outcome["reason"],
    }


def query_view(label, settings, blocks, requests, identifiers):
    snapshot = settings["preState"]
    head = blocks[-1] if blocks else settings.get("startingTip") or {}
    height, block_hash = head.get("height"), head.get("hash")
    by_position, ended, history = {}, {}, {}
    for block in blocks:
        for outcome in block["outcomes"]:
            coord = coordinate(block, outcome)
            row = transaction_query(coord, outcome, snapshot)
            by_position[coord] = row
            if outcome.get("grantId") is not None:
                history.setdefault(outcome["grantId"], []).append({
                    key: row[key] for key in ("position", "status", "actualSpent", "failureReason")
                })
            for grant_id, prior, current in outcome["changes"]["grants"]:
                if prior is not None and current is None:
                    ended[grant_id] = (prior, ended_grant_state(outcome), position(coord))
            snapshot = outcome["afterState"]

    current_rows = grant_rows(snapshot)
    by_grant = []
    for grant_id in identifiers:
        grant = current_rows.get(grant_id)
        prior, terminal, end = ended.get(grant_id, (None, UNKNOWN, None))
        state = terminal if grant is None else live_grant_state(grant, snapshot, height)
        evidence = grant or prior
        by_grant.append({
            "grantId": grant_id, "status": state,
            "owner": evidence[1] if evidence else UNKNOWN,
            "agent": evidence[2] if evidence else UNKNOWN,
            "assetId": evidence[3] if evidence else UNKNOWN,
            "remaining": remaining(grant, state),
            "remainingBeforeEnd": prior[5] if prior is not None else UNKNOWN,
            "endedAt": end, "history": history.get(grant_id, []),
        })
    view = {
        "network": settings["network"], "rulesSha256": RULES_SHA256,
        "activationHeight": settings.get("activationHeight"),
        "height": height, "blockHash": block_hash,
    }
    if "futureActivationHeights" in settings:
        view["futureActivationHeights"] = settings["futureActivationHeights"]
    return {
        "label": label, "view": view, "byGrantId": by_grant,
        "byTransaction": [by_position[c] if c in by_position else transaction_query(c) for c in requests],
    }


def confirmed_queries(settings, replayed):
    """Lookup expectations in each verified view, using only committed outcomes."""
    if "commonBlocks" in settings:
        input_blocks = settings["commonBlocks"] + settings["oldBlocks"] + settings["newBlocks"]
        # Fixed fork goldens have exactly one common block. For arbitrary inputs
        # acquire the full common history from the independent replay.
        common = ([replayed["ancestor"]] if len(settings["commonBlocks"]) == 1
                  else Replay(settings).follow(settings["commonBlocks"])["blocks"])
        views = [
            ("oldTip", common + replayed["oldBlocks"]),
            ("commonAncestor", common),
            ("replacementTip", common + replayed["newBlocks"]),
        ]
    else:
        input_blocks = settings["blocks"]
        views = [("verifiedTip", replayed["blocks"])]
    requests = sorted({coordinate(block, tx) for block in input_blocks for tx in block["transactions"]})
    identifiers = set(grant_rows(settings["preState"]))
    for _, blocks in views:
        identifiers.update(
            outcome["grantId"] for block in blocks for outcome in block["outcomes"]
            if outcome.get("grantId") is not None
        )
    if not identifiers:
        identifiers.add(sha256(b"synthetic query for an absent grant").hexdigest())
    return [query_view(label, settings, blocks, requests, sorted(identifiers)) for label, blocks in views]


def first_difference(expected, actual, path="$"):
    if type(expected) is not type(actual):
        return path
    if isinstance(expected, dict):
        for key in sorted(expected.keys() ^ actual.keys()):
            return f"{path}.{key} (key presence)"
        children = ((f"{path}.{key}", value, actual[key]) for key, value in expected.items())
    elif isinstance(expected, list):
        if len(expected) != len(actual):
            return f"{path}.length"
        children = ((f"{path}[{i}]", a, b) for i, (a, b) in enumerate(zip(expected, actual)))
    else:
        return None if expected == actual else path
    for child, left, right in children:
        difference = first_difference(left, right, child)
        if difference is not None:
            return difference
    return None


class ForkDifference(Exception):
    def __init__(self, detail):
        super().__init__(detail["field"])
        self.detail = detail


def compare_blocks(left, right):
    for index, (a, b) in enumerate(zip(left, right)):
        if a["canonicalHex"] != b["canonicalHex"]:
            raw_a, raw_b = bytes.fromhex(a["canonicalHex"]), bytes.fromhex(b["canonicalHex"])
            different_byte = next((i for i, (x, y) in enumerate(zip(raw_a, raw_b)) if x != y),
                                  min(len(raw_a), len(raw_b)))
            path = first_difference(json.loads(raw_a), json.loads(raw_b)) or "$.canonicalHex"
            raise ForkDifference({"index": index, "height": a["height"], "hash": a["hash"],
                                  "field": path, "firstByteOffset": different_byte})
        difference = first_difference(a, b)
        if difference is not None:
            raise ForkDifference({"index": index, "height": a["height"], "hash": a["hash"],
                                  "field": difference})
    if len(left) != len(right):
        excess = (left if len(left) > len(right) else right)[min(len(left), len(right))]
        raise ForkDifference({"height": excess["height"], "hash": excess["hash"],
                              "field": "$.blocks.length"})


def fork_replay(settings):
    chain = Replay(settings)
    common = settings["commonBlocks"]
    old_branch = chain.follow(common + settings["oldBlocks"])
    if old_branch["status"] != "OK" or not common:
        raise ValueError("fork fixture requires a committed common ancestor and complete old branch")
    chain.rewind_to(len(common))
    ancestor = chain.history[-1]
    # First verify the undo itself, even if the first new block overwrites a restored row.
    compare_blocks([{**ancestor, **canonical_view(chain.state)}], [ancestor])
    replayed = chain.follow(settings["newBlocks"])
    direct = Replay(settings).follow(common + settings["newBlocks"])
    compare_blocks(chain.history, direct["blocks"])
    if replayed["status"] != "OK" or direct["status"] != "OK":
        raise ValueError("fork fixture requires complete replacement blocks")
    return {"oldBlocks": old_branch["blocks"][len(common):], "newBlocks": replayed["blocks"],
            "ancestor": ancestor}


def fork_builders(rng, network):
    def transaction(op, signers, outputs, **fields):
        data = encode(network, {"operation": op, "authInput": 0, **fields})
        inputs = [{"prevoutScriptPubKeyHex": script.hex(), "witnessType": "P2TR_KEY_PATH",
                   "sighashType": 0, "outpoint": {"txid": rng.randbytes(32).hex(), "vout": 0}}
                  for script in signers]
        return {"txid": rng.randbytes(32).hex(), "inputs": inputs, "payloadHex": data.hex(),
                "outputs": [{"scriptPubKeyHex": s.hex(), "valueSats": "330"} for s in outputs]
                + [{"scriptPubKeyHex": push(data), "valueSats": "0"}]}

    def block(at, *transactions):
        sequence = [{**tx, "txIndex": index} for index, tx in enumerate(transactions)]
        rng.shuffle(sequence)
        return {"height": at, "hash": rng.randbytes(32).hex(), "transactions": sequence}

    return transaction, block


def synthetic_fork(rng):
    """Stage-one generator retained for exact single-group reproductions."""
    network, height = 3, rng.randrange(100, 400_000)
    script_a, script_b, script_c, script_d = (bytes((0x51, 0x20)) + bytes([i]) * 32
                                               for i in range(11, 15))
    owner, agent = account(script_a), account(script_b)
    deploy_txid = rng.randbytes(32)
    asset = tagged("AIBRC/asset/v1", bytes([network]) + deploy_txid + b"\0\0FORK").hex()
    state = {
        "assets": [{"assetId": asset, "name": "FORK", "network": network, "totalSupply": "500",
                    "deployTxid": deploy_txid.hex(), "ownerOutputIndex": 0, "locator": [1, 0]}],
        "names": [["FORK", asset]], "locators": [["1:0", asset]],
        "balances": [[f"{asset}:{owner}", "500"]],
    }
    transaction, block = fork_builders(rng, network)

    def delegate(cap, epoch=ZERO32, group=ZERO32, left=0):
        commit = derive("expectedContext", network, owner=owner, agent=agent, assetId=asset,
                        currentE=epoch, currentG=group, currentRemaining=left)
        return transaction("delegate", (script_a, script_a), (script_b,), assetId=asset,
                           agentOutput=0, amount=str(cap), expiry=height + 4, expectedContext=commit)

    def pay(identifier, amount):
        return transaction("transfer_for", (script_b, script_d), (script_c,), grantId=identifier,
                           items=[[0, str(amount)]])

    cap = rng.randrange(40, 100)
    spend = rng.randrange(1, cap)
    first = delegate(cap)
    common = block(height, first, transaction("revoke_all", (script_d,), (script_c,)))
    old_id = derive("grantId", network, owner=owner, assetId=asset, txid=first["txid"])
    group = derive("newG", network, owner=owner, agent=agent, assetId=asset,
                   blockHash=common["hash"], txid=first["txid"])
    revoke = transaction("revoke", (script_a,), (script_c,), grantId=old_id)
    all_permissions = transaction("revoke_all", (script_a,), (script_c,))
    first_payment = pay(old_id, spend)
    old_order = [first_payment, rng.choice([revoke, all_permissions])]
    if rng.randrange(2):
        old_order.reverse()
    old_blocks = [block(height + 1, *old_order), block(height + 2)]

    if rng.randrange(2):
        # Test the lost same-block race, then clean up and open a fresh grant.
        next_block = block(height + 1, all_permissions, first_payment, revoke)
        epoch = derive("newE", network, owner=owner, blockHash=next_block["hash"],
                       txid=all_permissions["txid"])
        expected_binding = (epoch, group, 0)
        new_blocks = [next_block]
    else:
        # Interleave an optional stale replacement with the same actual payment.
        stale = delegate(cap, group=group, left=cap)
        new_blocks = [block(height + 1, first_payment, stale)]
        expected_binding = (ZERO32, group, cap - spend)
    next_cap = rng.randrange(5, 30)
    new_grant = delegate(next_cap, *expected_binding)
    new_blocks.append(block(height + 2, new_grant))
    new_id = derive("grantId", network, owner=owner, assetId=asset, txid=new_grant["txid"])
    new_blocks.append(block(height + 3, pay(new_id, rng.randint(1, next_cap))))
    return {"network": network, "activationHeight": height, "preState": state,
            "commonBlocks": [common], "oldBlocks": old_blocks, "newBlocks": new_blocks}


def multi_group_fork(rng):
    """Share owners, agents and assets across groups so wrongly scoped writes show up."""
    network, height = 3, rng.randrange(100, 400_000)
    owner_a, owner_b, agent_c, agent_d, receiver, fee = (
        b"\x51\x20" + bytes([i]) * 32 for i in range(21, 27))
    transaction, block = fork_builders(rng, network)
    state = {"assets": [], "names": [], "locators": [], "balances": []}
    assets = []
    for index, name in enumerate(("FORK_X", "FORK_Y")):
        deploy = rng.randbytes(32)
        asset = tagged("AIBRC/asset/v1", bytes([network]) + deploy + b"\0\0" + name.encode()).hex()
        assets.append(asset)
        state["assets"].append({"assetId": asset, "name": name, "network": network, "totalSupply": "800",
                                "deployTxid": deploy.hex(), "ownerOutputIndex": 0, "locator": [1, index]})
        state["names"].append([name, asset])
        state["locators"].append([f"1:{index}", asset])
        state["balances"].extend([[f"{asset}:{account(owner)}", "400"] for owner in (owner_a, owner_b)])
    state = State(state).snapshot()
    x, y = assets
    groups = [(owner_a, agent_c, x), (owner_a, agent_d, x), (owner_b, agent_c, x),
              (owner_a, agent_c, y), (owner_b, agent_d, y)]

    def delegate(group, cap, epoch=ZERO32, revision=ZERO32, left=0):
        owner, agent, asset = group
        context = derive("expectedContext", network, owner=account(owner), agent=account(agent),
                         assetId=asset, currentE=epoch, currentG=revision, currentRemaining=left)
        return transaction("delegate", (owner, owner), (agent,), assetId=asset, agentOutput=0,
                           amount=str(cap), expiry=height + 4, expectedContext=context)

    def grant_id(group, original):
        owner, _, asset = group
        return derive("grantId", network, owner=account(owner), assetId=asset, txid=original["txid"])

    def pay(group, identifier, amount):
        owner, agent, _ = group
        target = rng.choice((owner, receiver))
        return transaction("transfer_for", (agent, fee), (target,), grantId=identifier,
                           items=[[0, str(amount)]])

    limits = [rng.randrange(40, 100) for _ in groups]
    first_grants = [delegate(group, cap) for group, cap in zip(groups, limits, strict=True)]
    common = block(height, *first_grants)
    ids = [grant_id(group, tx) for group, tx in zip(groups, first_grants, strict=True)]
    amounts = [rng.randrange(1, 16) for _ in groups]
    payments = [pay(group, identifier, amount)
                for group, identifier, amount in zip(groups, ids, amounts, strict=True)]
    focus = rng.randrange(len(groups))
    owner, agent, asset = focus_group = groups[focus]
    revision = derive("newG", network, owner=account(owner), agent=account(agent), assetId=asset,
                      blockHash=common["hash"], txid=first_grants[focus]["txid"])
    single = transaction("revoke", (owner,), (receiver,), grantId=ids[focus])

    old_order = [*payments, single]
    rng.shuffle(old_order)
    old_only_grant = delegate((owner_b, agent_d, x), 17)
    old_blocks = [block(height + 1, *old_order), block(height + 2, old_only_grant)]

    stale = delegate(focus_group, 19, revision=revision, left=limits[focus])
    payment_order = payments[:]
    rng.shuffle(payment_order)
    if rng.randrange(2):
        revoke_all = transaction("revoke_all", (owner,), (receiver,))
        # In this branch every group of the same owner is tested after the
        # global invalidation. The other owner's original payments still pass.
        first_new = block(height + 1, revoke_all, *payment_order, stale, single)
        epoch = derive("newE", network, owner=account(owner), blockHash=first_new["hash"],
                       txid=revoke_all["txid"])
        left = 0
    else:
        first_new = block(height + 1, *payment_order, stale)
        epoch, left = ZERO32, limits[focus] - amounts[focus]
    next_cap = rng.randrange(5, 31)
    replacement = delegate(focus_group, next_cap, epoch, revision, left)
    after_grant = block(height + 2, replacement)
    focus_payment = pay(focus_group, grant_id(focus_group, replacement), rng.randint(1, next_cap))
    another = rng.choice([i for i, group in enumerate(groups) if group[0] != owner])
    unrelated_payment = pay(groups[another], ids[another], 1)
    final = block(height + 3, focus_payment, unrelated_payment)
    return {"network": network, "activationHeight": height, "preState": state,
            "commonBlocks": [common], "oldBlocks": old_blocks,
            "newBlocks": [first_new, after_grant, final]}


def verify_fixture(case):
    settings = case["input"]
    mode = case["mode"]
    if mode in ("replay", "manualV1"):
        return Replay(settings).follow(settings["blocks"])
    if mode == "fork":
        return fork_replay(settings)
    if mode == "canonical":
        return canonical_view(State(settings["state"]).snapshot())
    if mode == "formula":
        return formula_result(settings["formula"], settings["network"], settings)
    if mode == "wire":
        tx = settings["transaction"]
        payload = bytes.fromhex(tx["payloadHex"])
        if markers(tx["outputs"]) != [Marker(payload)]:
            raise ValueError("encoder fixture does not match the output marker")
        header(payload, settings["network"])
        if payload[4] != 2:
            raise ValueError("encoder fixture must contain V2")
        return {"encodedPayloadHex": encode(settings["network"], settings["fields"]).hex(),
                "bytes": len(payload), "decoded": decode_v2(payload)}
    raise ValueError(f"unhandled fixture mode {mode}")


def verify_bundle(bundle, selected):
    passed, query_counts = Counter(), Counter()
    for case in bundle["cases"]:
        identifier = case["id"]
        if selected and identifier not in selected:
            continue
        try:
            readback = verify_fixture(case)
        except (ValueError, Reject, ForkDifference) as error:
            raise ValueError(f"{identifier}: {error}") from error
        mismatch = first_difference(case["expected"], readback)
        if mismatch:
            raise ValueError(f"{identifier}: first different field {mismatch}")
        if "confirmedQueries" in case:
            views = confirmed_queries(case["input"], readback)
            mismatch = first_difference(case["confirmedQueries"], views, "$.confirmedQueries")
            if mismatch:
                raise ValueError(f"{identifier}: first different field {mismatch}")
            query_counts.update(cases=1, views=len(views),
                                byGrantId=sum(len(v["byGrantId"]) for v in views),
                                byTransaction=sum(len(v["byTransaction"]) for v in views))
        passed[case["group"]] += 1
    if selected and sum(passed.values()) != len(selected):
        raise ValueError("selection includes an unknown or duplicated fixture ID")
    return {"passed": sum(passed.values()), "byGroup": dict(passed),
            "notExecutedV1Controls": [], "confirmedQueries": dict(query_counts)}


def random_forks(seed, count, *, legacy=False):
    if count < 1:
        raise ValueError("number of forks must be positive")
    rng = random.Random(seed)
    coverage = Counter()
    generator = synthetic_fork if legacy else multi_group_fork
    minimum = {}
    for index in range(count):
        settings = generator(rng)
        try:
            tested = fork_replay(settings)
        except ForkDifference as error:
            return {"status": "DIFFERENT", "seed": seed, "caseIndex": index,
                    "firstDifference": error.detail, "input": settings}
        if not legacy:
            ancestor = json.loads(bytes.fromhex(tested["ancestor"]["canonicalHex"]))
            rows = ancestor.get("grants", [])
            dimensions = {
                "owners": len({row[1] for row in rows}), "agents": len({row[2] for row in rows}),
                "assets": len({row[3] for row in rows}), "groups": len(rows),
            }
            if dimensions != {"owners": 2, "agents": 2, "assets": 2, "groups": 5}:
                return {"status": "DIFFERENT", "seed": seed, "caseIndex": index, "input": settings,
                        "firstDifference": {"height": tested["ancestor"]["height"],
                                            "field": "$.grants", "actualDimensions": dimensions}}
            minimum = {key: min(minimum.get(key, size), size) for key, size in dimensions.items()}
        for branch in ("oldBlocks", "newBlocks"):
            for block in tested[branch]:
                for tx in block["outcomes"]:
                    coverage[f"{branch}/{tx['operation']}/{tx['reason']}"] += 1
    result = {"status": "MATCH", "seed": seed, "forks": count,
              "outcomes": dict(sorted(coverage.items()))}
    if minimum:
        result["minAncestorDimensions"] = minimum
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    verify = commands.add_parser("verify", help="compare results to the committed independent vectors")
    verify.add_argument("path", nargs="?", type=Path, default=DEFAULT_FIXTURES)
    verify.add_argument("--case", action="append", help="one exact fixture ID (repeatable)")
    replay = commands.add_parser("replay", help="read a replay or fork input JSON from file or stdin")
    replay.add_argument("path", nargs="?", type=Path)
    replay.add_argument("--confirmed-queries", action="store_true",
                        help="include independent confirmed query expectations")
    forks = commands.add_parser("fork", help="generate a reproducible cross-fork replay comparison")
    forks.add_argument("--seed", type=lambda s: int(s, 0), required=True)
    forks.add_argument("--cases", type=int, default=64)
    forks.add_argument("--legacy", action="store_true", help="use the exact stage-one generator")
    args = parser.parse_args(sys.argv[1:] or ["verify"])
    try:
        if args.command == "verify":
            result = verify_bundle(json.loads(args.path.read_text(encoding="utf-8")), args.case)
        elif args.command == "replay":
            text = sys.stdin.read() if args.path is None else args.path.read_text(encoding="utf-8")
            item = json.loads(text)
            settings = item.get("input", item)
            if "commonBlocks" in settings:
                result = fork_replay(settings)
            else:
                result = Replay(settings).follow(settings["blocks"])
            if args.confirmed_queries:
                result = {"replay": result, "confirmedQueries": confirmed_queries(settings, result)}
        else:
            result = random_forks(args.seed, args.cases, legacy=args.legacy)
    except (ValueError, Reject, ForkDifference) as error:
        print(error, file=sys.stderr)
        return 1
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 1 if result.get("status") == "DIFFERENT" else 0


if __name__ == "__main__":
    sys.exit(main())
