#!/usr/bin/env python3
"""Bounded Kafka round trip using the existing kcat client on the local evaluation."""
import subprocess
import uuid


def verify(run=subprocess.run):
    identifier = uuid.uuid4().hex
    topic = "kubemq-evaluation-" + identifier
    payload = ("kubemq-check-" + identifier + "\n").encode()
    common = ["kcat", "-b", "127.0.0.1:9092", "-t", topic]
    run(common + ["-P"], input=payload, capture_output=True, timeout=20, check=True)
    received = run(common + ["-C", "-o", "beginning", "-c", "1", "-e", "-q"], capture_output=True, timeout=20, check=True)
    if received.stdout != payload:
        raise RuntimeError("The consumed message differs from the unique produced message")
    return topic


if __name__ == "__main__":
    try:
        topic = verify()
    except (OSError, subprocess.SubprocessError, RuntimeError) as error:
        raise SystemExit("Kafka verification failed: " + str(error))
    print("Kafka producer and consumer verified the exact unique message in " + topic)
