"""Local evaluation for Programming Problem 2: RAM Stick Permutations"""

import importlib.util
from pathlib import Path

SAMPLE_TESTS = [
    [1],
    [2, 1],
    [2, 1, 3],
    [3, 1, 4, 2],
    [2, 4, 1, 3, 5],
    [5, 2, 6, 1, 3, 4],
    [4, 7, 2, 5, 1, 6, 3],
    [3, 1, 7, 5, 2, 8, 4, 6],
    [6, 2, 9, 4, 1, 7, 3, 8, 5],
    [8, 3, 6, 1, 9, 4, 10, 2, 7, 5],
]


def run_test(solve, secret):
    n = len(secret)
    queries = [0]
    answer = [None]

    def query(cmd):
        parts = cmd.strip().split()
        op, perm = parts[0], [int(x) for x in parts[1:]]
        if op == "!":
            answer[0] = perm
            raise StopIteration
        if queries[0] >= n:
            raise Exception("Query limit exceeded")
        queries[0] += 1
        return str(sum(2 ** (i + 1) for i in range(n) if perm[i] == secret[i]))

    try:
        solve(n, query)
    except StopIteration:
        pass
    return answer[0] == secret, queries[0]


if __name__ == "__main__":
    spec = importlib.util.spec_from_file_location(
        "solution", Path(__file__).parent / "solution.py"
    )
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)

    passed = 0
    for i, secret in enumerate(SAMPLE_TESTS, 1):
        try:
            ok, q = run_test(mod.solve, secret)
            msg = f"({q}/{len(secret)} queries)" if ok else "WRONG"
        except Exception as e:
            ok, msg = False, str(e)
        print(f"Test {i}: {'PASS' if ok else 'FAIL'} {msg}")
        passed += ok
    print(f"\n{passed}/{len(SAMPLE_TESTS)} passed")
