#!/usr/bin/env python3
#
# Testing tool for the Cheese Comparison problem
#
# Usage:
#
#   python3 testing_tool.py -f inputfile <program>
#
#
# Use the -f parameter to specify the input file, e.g. 1.in.
# Format of the input file:
# - One line with one integer n, the number of cheese wheels.
# - One lines with w integers, the weights of the cheese wheels.
# E.g.:
# 3
# 1 2 3
#
# If you have a C++ solution stored in a file called "sol.cpp",
# you must first compile using "g++ sol.cpp -o sol" and then
# invoke the testing tool with:
#
#   python3 testing_tool.py -f 1.in ./sol
#
# If you have a Python solution that you would run using
# "pypy3 solution.py", you could invoke the testing tool with:
#
#   python3 testing_tool.py -f 1.in pypy3 solution.py
#
# If you have a Java solution that you would run using
# "java MyClass", you could invoke the testing tool with:
#
#   python3 testing_tool.py -f 1.in java MyClass
#
# If you have a Kotlin solution stored in a file called "Sol.kt",
# you must first compile using "kotlinc Sol.kt" and then
# invoke the testing tool with:
#
#   python3 testing_tool.py -f 1.in kotlin Sol
#
# The tool is provided as-is, and you should feel free to make
# whatever alterations or augmentations you like to it.
#
# The tool attempts to detect and report common errors, but it is not guaranteed
# that a program that passes the testing tool will be accepted.
# Specifically, this testing tool only uses fixed grid,
# while your program will be tested against an adaptive interactor.

import argparse
import subprocess
import traceback


def write(p, line):
    assert p.poll() is None, "Program terminated early"
    print(f"Write: {line}", flush=True)
    p.stdin.write(f"{line}\n")
    p.stdin.flush()


def read(p):
    assert p.poll() is None, "Program terminated early"
    line = p.stdout.readline().strip()
    assert (
        line != ""
    ), "Read empty line or closed output pipe. Make sure that your program started successfully."
    print(f"Read: {line}", flush=True)
    return line


parser = argparse.ArgumentParser(
    description="Testing tool for the Cheese Comparison problem"
)
parser.add_argument(
    "-f",
    dest="inputfile",
    metavar="inputfile",
    default=None,
    type=argparse.FileType("r"),
    required=True,
    help="The input file to use.",
)
parser.add_argument("program", nargs="+", help="Invocation of your solution")

args = parser.parse_args()

with args.inputfile as f:
    lines = f.readlines()
    assert len(lines) > 0

    n = int(lines[0])
    ws = list(map(int, lines[1].split()))

queries = 0
max_queries = 20000

with subprocess.Popen(
    " ".join(args.program),
    shell=True,
    stdout=subprocess.PIPE,
    stdin=subprocess.PIPE,
    universal_newlines=True,
) as p:
    try:
        write(p, f"{n}")

        while True:
            line = read(p).split()
            if line[0] == "?":
                queries += 1
                i = int(line[1]) - 1
                j = int(line[2]) - 1
                if ws[i] == ws[j]:
                    write(p, "=")
                if ws[i] < ws[j]:
                    write(p, "<")
                if ws[i] > ws[j]:
                    write(p, ">")
            elif line[0] == "!":
                for i in range(0, n - 1):
                    assert (
                        ws[int(line[i + 1]) - 1] <= ws[int(line[i + 2]) - 1]
                    ), "Wrong answer"
                break
            else:
                assert False, f"Unknown command: {line[0]}"

        assert (
            p.stdout.readline() == ""
        ), "Your submission printed extra data after printing the answer."
        assert p.wait() == 0, "Your submission did not exit cleanly after finishing."

        assert (
            queries <= max_queries
        ), f"Used {queries} queries, which is more than the allowed {max_queries}."

        print(f"\nSuccess.\nQueries used: {queries}\n")

    except AssertionError as e:
        print()
        print(f"Error: {e}")
        print()
        try:
            p.wait(timeout=2)
        except subprocess.TimeoutExpired:
            print("Killing your submission after 2 second timeout.")
            p.kill()

    except Exception as e:
        print()
        traceback.print_exc()
        print()
        try:
            p.wait(timeout=2)
        except subprocess.TimeoutExpired:
            print("Killing your submission after 2 second timeout.")
            p.kill()
        raise e

    finally:
        print(f"Exit code: {p.wait()}\n", flush=True)
