"""Constructed example. Python 3.9+. No model, network, or deployment calls.

The two fixtures are authored, not captured from a real incident. The boundary
covers one model request and one tool request. It is not a general recorder.
"""
from copy import deepcopy

PROMPT = "Inspect CI for main and return the tool call."
MODEL_REQUEST = {"prompt": PROMPT, "model": "example-model-v1"}
TOOL_REQUEST = {"name": "get_ci", "args": {"ref": "main"}}
FAILED = {"status": "failed", "commit": "old-commit"}
PASSED = {"status": "passed", "commit": "new-commit"}
HISTORY = [
    ("model", MODEL_REQUEST, TOOL_REQUEST),
    ("tool", TOOL_REQUEST, FAILED),
]


class ReplayDivergence(Exception):
    pass


class FrozenIO:
    def __init__(self):
        self.events = deepcopy(HISTORY)
        self.cursor = 0

    def call(self, kind, request):
        if self.cursor == len(self.events):
            raise ReplayDivergence("recording exhausted")
        expected_kind, expected_request, response = self.events[self.cursor]
        if (kind, request) != (expected_kind, expected_request):
            raise ReplayDivergence(f"request changed at event {self.cursor}")
        self.cursor += 1
        return deepcopy(response)

    def finish(self):
        if self.cursor != len(self.events):
            raise ReplayDivergence("recording not fully consumed")


class ChangedWorld:
    """A second authored fixture simulates a later observation. Not a live API."""
    def call(self, kind, request):
        if (kind, request) == ("model", MODEL_REQUEST):
            return deepcopy(TOOL_REQUEST)
        if (kind, request) == ("tool", TOOL_REQUEST):
            return deepcopy(PASSED)
        raise ReplayDivergence("unexpected simulated request")

    def finish(self):
        pass


def buggy_gate(result):
    return "publish-intent" if result["status"] else "stop"


def fixed_gate(result):
    return "publish-intent" if result["status"] == "passed" else "stop"


def run(io, gate, prompt=PROMPT):
    plan = io.call("model", {**MODEL_REQUEST, "prompt": prompt})
    result = io.call("tool", plan)
    intent = gate(result)
    io.finish()
    return intent  # No effect executor exists in this example.


def main():
    assert run(FrozenIO(), buggy_gate) == "publish-intent"
    print("historical replay: publish-intent on failed CI (bug reproduced)")
    assert run(ChangedWorld(), buggy_gate) == "publish-intent"
    print("changed world: publish-intent on passed CI (bug hidden)")
    assert run(FrozenIO(), fixed_gate) == "stop"
    print("code regression test: stop on failed CI (fix handles old input)")
    try:
        run(FrozenIO(), buggy_gate, prompt="Inspect CI for release instead.")
    except ReplayDivergence as error:
        print(f"prompt edit: {error} (fresh model evaluation required)")
    else:
        raise AssertionError("Changed prompt incorrectly accepted")
    try:
        io = FrozenIO()
        io.call("model", MODEL_REQUEST)
        io.call("tool", {"name": "get_ci", "args": {"ref": "release"}})
    except ReplayDivergence:
        print("tool argument edit: rejected at event 1")
    else:
        raise AssertionError("Changed tool arguments incorrectly accepted")
    for operation in (lambda io: io.finish(), lambda io: io.call("tool", TOOL_REQUEST)):
        try:
            operation(FrozenIO())
        except ReplayDivergence:
            pass
        else:
            raise AssertionError("Incomplete or reordered history accepted")


if __name__ == "__main__":
    main()
