#!/usr/bin/env python3
#
# Testing tool for the Involuted Interference problem
#
# Usage:
#
#   python3 testing_tool.py -f inputfile --seed seed <program invocation>
#
#
# Use the -f parameter to specify the input file, e.g. 1.in.
# Use the --seed parameter to change the random seed for the input
# in pass 3, e.g. 43.
# The input file should contain the following:
# - The first line contains one bitstring $a$.
# - The second line contains one bitstring $b$.

# You can compile and run your solution as follows:

# C++:
#   g++ solution.cpp
#   python3 testing_tool.py -f 1.in --seed 43 ./a.out

# Python:
#   python3 testing_tool.py -f 1.in --seed 43 python3 ./solution.py

# Java:
#   javac solution.java
#   python3 testing_tool.py -f 1.in --seed 43 java solution

# Kotlin:
#   kotlinc solution.kt
#   python3 testing_tool.py -f 1.in --seed 43 kotlin solutionKt


# 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 an exhaustive test.
# It is not guaranteed that a program that passes this testing tool will be accepted.


import argparse
import subprocess
import traceback
import random

parser = argparse.ArgumentParser(description="Testing tool for problem: Involuted Interference.")
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(
    "--seed",
    default=42,
    type=int,
    required=False,
    help="The random seed for third pass input.",
)
parser.add_argument("program", nargs="+", help="Invocation of your solution")

args = parser.parse_args()

class WrongAnswer(Exception): pass
def wa_assert(condition: bool, message: str):
    if not condition:
        raise WrongAnswer(message)


def single_pass(pass_no: int, name: str, bistring: str) -> str:
    with (
        subprocess.Popen(
            " ".join(args.program),
            shell=True,
            stdout=subprocess.PIPE,
            stdin=subprocess.PIPE,
            universal_newlines=True,
        ) as p,
    ):
        assert p.stdin is not None and p.stdout is not None

        raw = "\n".join([name, bistring])
        print(f"Pass {pass_no} input:\n{raw}")
        print()

        stdout, stderr = p.communicate(input=raw)
        output = [word for line in stdout.strip().split('\n') for word in line.strip().split()]

        if pass_no == 1 or pass_no == 2:
            wa_assert(len(output) == 1,
                f"Your submission printed {len(output)} string(s), expected 1 string.")
        else:
            wa_assert(len(output) == 2,
                f"Your submission printed {len(output)} string(s), expected 2 strings.")

        print(f"Pass {pass_no} exit code: {p.returncode}")
        print(f"Pass {pass_no} output:")
        print()
        print(stdout, flush=True)
        
        if pass_no == 1 or pass_no == 2:
            s = output[0]

            wa_assert(1 <= len(s) <= 2026,
                f"Your bitstring must has length {len(s)}, it must be between 1 and 2026.")
            for c in s:
                wa_assert(c in "01",
                    f"Your bitstring contains character {c}, only '0' and '1' is allowed.")

            return s
        else:
            return output[0], output[1]

try:
    with args.inputfile as f:
        # Parse input
        lines = [line.strip() for line in f.readlines()]
        assert len(lines) >= 2, "Input file should contain two lines with a bitstring each."
        a = lines[0]
        b = lines[1]
        assert 1 <= len(a) <= 250, "Input bitstrings should have length between 1 and 250 inclusive."
        assert 1 <= len(b) <= 250, "Input bitstrings should have length between 1 and 250 inclusive."
        assert a.count('0') + a.count('1') == len(a), "Input bitstrings should only contain '0' and '1'."
        assert b.count('0') + b.count('1') == len(b), "Input bitstrings should only contain '0' and '1'."

    s_a = single_pass(1, "Alice", a)
    s_b = single_pass(2, "Bob", b)

    random.seed(args.seed)

    offset_a = random.randint(0, len(s_a) - 1)
    offset_b = random.randint(0, len(s_b) - 1)
    print(f"Information to help you debugging:")
    print(f"s_a' starts at the {offset_a + 1}th position of the infinite concatenation.")
    print(f"s_b' starts at the {offset_b + 1}th position of the infinite concatenation.")
    print()

    s = ""
    for i in range(2026):
        # awful unreadable code
        s += chr(48 + ((ord(s_a[(offset_a + i) % len(s_a)])
                       | ord(s_b[(offset_b + i) % len(s_b)])) & 1))

    team_a, team_b = single_pass(3, "Carol", s)

    wa_assert(team_a == a, f"(a) Got '{team_a}', expected '{a}'")
    wa_assert(team_b == b, f"(b) Got '{team_b}', expected '{b}'")

    print("Accepted.")

except WrongAnswer as e:
    print()
    print(f"Wrong Answer: {e}")
    print()
    exit(1)

except AssertionError as e:
    print()
    print(f"Error: {e}")
    print()
    exit(1)

except Exception:
    print()
    print("Unexpected error:")
    traceback.print_exc()
    print()
    exit(1)
