#! /usr/bin/python3

import argparse
import json
import os
import random
import shutil
import sys

parser = argparse.ArgumentParser("Generate a puzzle")
parser.add_argument("--file", dest="file", help="File to provide, instead of puzzle")
parser.add_argument("--answer", dest="answer", help="Answer to check, instead of providing puzzle")
args = parser.parse_args()

seed = hash(os.getenv("SEED"))
random.seed(seed)

words = ["apple", "pear", "peach", "tangerine", "orange", "potato", "carrot", "pea"]
answer = ' '.join(random.sample(words, 4))

if args.file:
    f = open(args.file, "rb")
    shutil.copyfileobj(f, sys.stdout.buffer)
elif args.answer:
    if args.answer == answer:
        print("correct")
    else:
        print("incorrect")
else:
    number = random.randint(20, 500)
    obj = {
        "Pre": {
            "Authors": ["neale"],
            "Body": (
                "<p>Dynamic puzzles are provided with a JSON-generating <code>mkpuzzles</code> program in the puzzle directory.</p>"
                "<p>You can write <code>mkpuzzles</code> in any language you like. This puzzle was written in Python 3.</p>"
                "<p>Here is some salad:<img src='salad.jpg'></p>"
            ),
            "Attachments": ["salad.jpg"],
        },
        "Answers": [
            answer,
        ],
        "Debug": {
            "Summary": "Dynamic puzzles",
            "Hints": [
                "Check the debug output to get the answer." ,
            ],
            "Errors": [],
            "Log": [
                "%d is a positive integer" % number,
            ],
        }
    }
    json.dump(obj, sys.stdout)