"""
Usage:

python eggs-test.py command n k h

Example with C++:
python eggs-test.py "./my_binary" 2 5 3

Example with Python:
python eggs-test.py "python my_code.py" 2 5 3

The script runs one test with the given values of n, k and h.
It then checks the answer and reports how many queries your program made.
"""

import subprocess
import sys


def run(command: str, n: int, k: int, h: int):
    if n < 1:
        sys.exit("n must be at least 1")
    if k < 1:
        sys.exit("k must be at least 1")
    if h < 1 or h > k:
        sys.exit("h must be between 1 and k")

    proc = subprocess.Popen(
        command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True
    )
    assert proc.stdin is not None
    assert proc.stdout is not None
    proc.stdin.write(f"{n} {k}\n".encode())
    proc.stdin.flush()

    query_count = 0

    while True:
        line = proc.stdout.readline()
        parts = line.split()
        if len(parts) != 2:
            sys.exit(f"Incorrect format:\n{line.decode()}")
        op = parts[0]
        x = int(parts[1])

        if op == b"?":
            # Query
            query_count += 1
            if n <= 0:
                print("No eggs left to drop!")
                break
            if x <= h:
                proc.stdin.write(b"Intact\n")
            else:
                proc.stdin.write(b"Broken\n")
                n -= 1
            proc.stdin.flush()
        elif op == b"!":
            # Answer
            if x == h:
                print("Correct answer!")
            else:
                print(f"Wrong answer: {x}")
            break
        else:
            sys.exit(f"Unexpected operation:\n{line.decode()}")

    print(f"Made {query_count} queries")


def usage():
    print(__doc__, end="")
    exit(2)


if __name__ == "__main__":
    if len(sys.argv) != 5:
        usage()

    command = sys.argv[1]
    n = int(sys.argv[2])
    k = int(sys.argv[3])
    h = int(sys.argv[4])

    run(command, n, k, h)
