
#!/usr/bin/env python3
"""Local "Memory Game" interactor. Usage: python3 sample_interactor.py solution_file [--verbose]

Any solution file or executable works, so solve.cpp, solve.c, solve.py, solve.java, solve.kt and solve all will work.

The input format for the sample interactor is as following:
N card1, card2, ..., card2N

You can pass the input on standard input, or redirect it from a file.
Example usage to test on the sample input:
echo "3 APPLE STAR FISH STAR FISH APPLE" | python3 sample_interactor.py solution_file.cpp
or
echo "3 APPLE STAR FISH STAR FISH APPLE" > sample_input; python3 sample_interactor.py solution_file < sample_input
"""
import argparse
import os
import signal
import subprocess
import sys
import tempfile
from pathlib import Path


class WrongAnswer(Exception):
    pass


def run_judge(proc, verbose):
    # Read test case from stdin.
    tokens = (word for line in sys.stdin for word in line.split())
    n = int(next(tokens))
    vals = [""] + [next(tokens) for _ in range(2 * n)]

    def send(s):
        if verbose:
            print(f"JUDGE -> {s}", file=sys.stderr)
        print(s, file=proc.stdin, flush=True)

    def receive():
        s = proc.stdout.readline()
        if not s:
            raise WrongAnswer("Program ended without submitting an answer")
        s = s.rstrip("\n")
        if verbose:
            print(f"SOLUTION -> {s}", file=sys.stderr)
        return s

    def get_int():
        s = receive()
        if s == "VICTORY":
            raise WrongAnswer("Game declared won, but not all pairs were removed")
        if not (s.isascii() and s.isdigit()):
            raise WrongAnswer(f"Invalid action: {s}")
        return int(s)

    def check(x):
        if not 1 <= x <= 2 * n:
            raise WrongAnswer("Invalid move index")
        if x in removed:
            raise WrongAnswer("Tried to pick up a removed card")

    removed = set()
    pairs_found = 0
    send(str(n))

    for _ in range(2 * n):
        if pairs_found == n:
            if receive() != "VICTORY":
                raise WrongAnswer("Expected VICTORY")
            if proc.stdout.read().split():
                raise WrongAnswer("Trailing output")
            return

        x = get_int()
        check(x)
        send(vals[x])

        y = get_int()
        check(y)
        if x == y:
            raise WrongAnswer("Tried to pick up the same card twice")
        send(vals[y])

        if vals[x] == vals[y]:
            removed.update((x, y))
            pairs_found += 1

    raise WrongAnswer("Too many queries used")




def solution_command(source, folder):
    source = Path(source).resolve()
    if not source.is_file():
        raise ValueError(f"File not found: {source}")

    if source.suffix in (".cpp", ".cc", ".cxx"):
        binary = Path(folder) / "solution"
        subprocess.run(
            ["g++", "-x", "c++", "-Wall", "-O2", "-static", "-pipe",
             "-o", str(binary), str(source)],
            check=True
        )
        return [str(binary)]
    if source.suffix == ".c":
        binary = Path(folder) / "solution"
        subprocess.run(
            ["gcc", "-x", "c", "-Wall", "-O2", "-static", "-pipe",
             "-o", str(binary), str(source), "-lm"],
            check=True
        )
        return [str(binary)]
    if source.suffix == ".py":
        return ["python3", "-u", str(source)]
    if source.suffix == ".java":
        subprocess.run(
            ["javac", "-encoding", "UTF-8", "-sourcepath", ".",
             "-d", str(folder), source.name],
            cwd=source.parent, check=True
        )
        return ["java", "-cp", str(folder), source.stem]
    if source.suffix == ".kt":
        subprocess.run(
            ["kotlinc", "-d", str(folder), str(source)],
            check=True
        )
        return ["kotlin", "-cp", str(folder), source.stem[0].upper() + source.stem[1:] + "Kt"]
    if os.access(source, os.X_OK):
        return [str(source)]
    raise ValueError("Unsupported file type")


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("solution", help="C++ source, Python script, Java file, or executable")
    parser.add_argument("--verbose", action="store_true", help="print every message to stderr")
    args = parser.parse_args()

    with tempfile.TemporaryDirectory(prefix="interactive-test-") as folder:
        try:
            command = solution_command(args.solution, folder)
        except (ValueError, OSError, subprocess.CalledProcessError) as exc:
            print(f"Compilation/setup failed: {exc}", file=sys.stderr)
            return 2

        proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                text=True, bufsize=1, start_new_session=True)
        try:
            run_judge(proc, args.verbose)
            proc.stdin.close()
            if proc.wait() != 0:
                print(f"Runtime error (exit code {proc.returncode})", file=sys.stderr)
                return 1
            print("AC: correct answer!", file=sys.stderr)
            return 0
        except WrongAnswer as exc:
            print(f"WA: {exc}", file=sys.stderr)
            return 1
        except (BrokenPipeError, ConnectionResetError):
            print("WA: solution closed its input", file=sys.stderr)
            return 1
        finally:
            if proc.poll() is None:
                os.killpg(proc.pid, signal.SIGKILL)
            proc.wait()
            proc.stdout.close()
            if not proc.stdin.closed:
                proc.stdin.close()


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print("Interrupted", file=sys.stderr)
        sys.exit(130)
