#!/usr/local/cpython-3.6/bin/python3

"""
Generate a gquiz2 input for a vocabulary test.

We assume questions and answers are each one line long.
We also assume that we want to ask the question+answer pairs in "both directions".
"""

import sys
import typing
import itertools


def usage(retval: typing.Optional[int]) -> None:
    """Output a usage message."""
    if retval in (0, None):
        write = sys.stdout.write
    else:
        write = sys.stderr.write

    write('Usage: {} --produce-speech\n'.format(sys.argv[0]))
    write('For an n question test, stdin should be n * 3 - 1 or n * 3 lines (the final empty line is optional)\n')
    write('\n')
    write('For example, a 3 question test can have stdin in the following form:\n')
    write('question1\nanswer1\n\nquestion2\nanswer2\n\nquestion3\nanswer3\n')

    sys.exit(retval)


def main() -> None:
    """Generate a two-way vocabulary test."""
    produce_speech = False

    while sys.argv[1:]:
        if sys.argv[1] == '--produce-speech':
            produce_speech = True
        elif sys.argv[1] in ('-h', '--help'):
            usage(0)
        else:
            sys.stderr.write('{}: unrecognized option: {}\n'.format(sys.argv[0], sys.argv[1]))
            usage(1)
        del sys.argv[1]

    lines = [line.rstrip() for line in sys.stdin.readlines()]
    # If the last line isn't empty, add an empty line at the end
    if lines[-1] != '':
        lines.append('')
    len_lines = len(lines)
    # Check if this input has a number of lines that is (now) a multiple of 3.
    if int(len_lines / 3) * 3 != len_lines:
        sys.stderr.write('{}: length of input is not a multiple of 3 plus 2\n'.format(sys.argv[0]))
        sys.exit(1)

    if produce_speech:
        sys.stdout.write('produce_speech\n')
    else:
        sys.stdout.write('\n')

    list_ = []
    for tripletno, (line1, line2, empty) in enumerate(itertools.zip_longest(lines[::3], lines[1::3], lines[2::3])):
        if empty != '':
            sys.stderr.write('{}: triplet {} (line {}) does not end with an empty line\n'.format(
                sys.argv[0],
                tripletno,
                tripletno * 3,
                ))
            sys.exit(1)
        list_.append('{}\n-\n{}\n'.format(line1, line2))
        list_.append('{}\n-\n{}\n'.format(line2, line1))
    sys.stdout.write('%%\n'.join(list_))


main()