#!/usr/bin/python3

# by John Goerzen
#
# Pass the test as $1
#
# Line one of test must be !gamename
# Empty lines and lines starting with ; are ignored.
# Lines starting with > will cause the system to wait for the prompt, then send
# the given text.  All other lines will be used to wait for those responses.

import pexpect
import sys
import time
import os
import os.path

def prompt(c):
    #sys.stderr.write("Waiting for prompt\n")
    c.expect_exact("\n>")
    #sys.stderr.write("Prompt wait 2\n")
    #c.expect_exact('Score: ')
    #sys.stderr.write("Prompt wait 3\n")
    #c.expect_exact('Moves: ')

testname = os.path.abspath(sys.argv[1])
testdir = os.path.dirname(testname)
os.chdir(testdir)

testfile = open(testname, "rt")
gamename = testfile.readline().strip()
if not gamename.startswith('!'):
    print("Error: expected !gamename on line 1")
    sys.exit(5)

gamename = gamename[1:]

c = pexpect.spawn('fizmo-console', ['-dh', '-ll', '80', gamename], timeout=5)
c.logfile = sys.stdout.buffer
# c.delaybeforesend = 0.01
c.setecho(False)

for line in testfile.readlines():
    line = line.strip()
    if line.startswith(';') or line == '':
        continue
    if line.startswith('>'):
        line = line[1:].strip()
        prompt(c)
        c.sendline(line)
        print(">>> %s" % line)
        sys.stdout.flush()
    else:
        sys.stderr.write("Waiting for: %s\n" % (line))
        c.expect_exact(line)

