"""Send one batch to the report consumer."""

import json
import sys

from chio_process import ProcessClient
from artifacts import save_receipt


def send_batch(client, items):
    sent = client.invoke(
        "send-order",
        "chio-ipc",
        "send_jobs",
        {"message_key": "order", "payload": {"items": items}},
    )
    if sent["verdict"] != "allow":
        raise RuntimeError(f"Send refused: {sent.get('reason')}")
    if sent["terminal_state"]["state"] != "completed":
        raise RuntimeError("Send outcome is uncertain; retain send-order")
    if sent["output"]["value"]["status"] != "sent":
        raise RuntimeError("Mailbox did not accept the batch")
    return sent


def main():
    bootstrap = json.load(sys.stdin)
    if bootstrap["schema"] != "chio.process.worker-bootstrap.v1":
        raise RuntimeError("Unsupported worker bootstrap")
    connection = bootstrap["connection"]
    client = ProcessClient(connection["socket_path"], connection["credential"])
    sent = send_batch(client, bootstrap["input"]["items"])
    save_receipt(bootstrap["input"]["directory"], sent["receipt_json"])
    # The host captures stdout for this attempt. Keep signed text unchanged.
    print(sent["receipt_json"])


if __name__ == "__main__":
    main()
