import argparse
import json
from pathlib import Path

parser = argparse.ArgumentParser(description="Check the handbook's two tool-call examples.")
parser.add_argument("provider_event", type=Path)
parser.add_argument("next_request", type=Path)
args = parser.parse_args()

event = json.loads(args.provider_event.read_text(encoding="utf-8"))
request = json.loads(args.next_request.read_text(encoding="utf-8"))
call = event["item"]
if event["type"] != "response.output_item.done" or call["type"] != "function_call":
    raise SystemExit("FAIL: expected a completed function call in the provider event")
if call["name"] != "exec_command":
    raise SystemExit("FAIL: expected exec_command")

call_id = call["call_id"]
outputs = [
    item["output"]
    for item in request["input"]
    if item["type"] == "function_call_output" and item["call_id"] == call_id
]
if len(outputs) != 1:
    raise SystemExit(f"FAIL: expected one result with call_id {call_id}, found {len(outputs)}")

lines = outputs[0].splitlines()
if "Process exited with code 0" not in lines or lines[-2:] != ["Output:", "tool harness"]:
    raise SystemExit("FAIL: expected exit code 0 and output 'tool harness'")

print(f"PASS: {call_id} matched exit code 0 and output 'tool harness'")
