"""Reproduce a failing test, propose a source edit and return a verified diff."""
from difflib import unified_diff
from agent_tools import ask, execute, workspace

SOURCE = """def shipping_cents(subtotal):
    return 0 if subtotal > 5000 else 599
"""
TEST = """from shipping import shipping_cents

for subtotal, expected in [(4999, 599), (5000, 0), (5001, 0)]:
    actual = shipping_cents(subtotal)
    assert actual == expected, (subtotal, expected, actual)
print("3 cases passed")
"""


def run():
    with workspace(block_network=True) as box:
        box.filesystem.write_text(SOURCE, "/work/shipping.py")
        box.filesystem.write_text(TEST, "/work/check.py")
        try:
            execute(box, "python3", "-B", "check.py")
        except RuntimeError as failure:
            if "AssertionError: (5000, 0, 599)" not in str(failure):
                raise
            print("Reproduced:", str(failure).splitlines()[-1])
            evidence = str(failure)
        else:
            raise RuntimeError("The starting implementation unexpectedly passed")
        for _ in range(2):
            candidate = ask("Repair shipping.py. Free shipping starts at 5000 cents. "
                            "Return its full source as JSON under code.\n" +
                            SOURCE + "\nTests:\n" + TEST + "\nFailure:\n" + evidence)["code"]
            box.filesystem.write_text(candidate, "/work/shipping.py")
            try:
                output = execute(box, "python3", "-B", "check.py").strip()
                if output != "3 cases passed":
                    raise RuntimeError("The test never confirmed all three cases passed")
                print(output)
            except RuntimeError as failure:
                evidence = candidate + "\n" + str(failure)
                continue
            print("".join(unified_diff(SOURCE.splitlines(True), candidate.splitlines(True),
                                      "a/shipping.py", "b/shipping.py")))
            return
        raise RuntimeError("Two proposals failed the original tests")


if __name__ == "__main__":
    run()
