#!/usr/bin/python3

import argparse
import locale
import puz
import requests
import os
import sys

locale.setlocale(locale.LC_ALL, "")

OEDIPUS_BASE = "http://web.tiscali.it/oedipus/images"

OEDIPUS_PUZZLES = [
    "15x10_01.puz",
    "15x10_02.puz",
    "15x10_03.puz",
    "15x10_04.puz",
]


class InvalidNumberException(Exception):
    pass


class PuzDownloader:
    def getPuzzle(self, number):
        index = number - 1
        if index not in range(len(OEDIPUS_PUZZLES)):
            raise InvalidNumberException

        r = requests.get(f"{OEDIPUS_BASE}/{OEDIPUS_PUZZLES[index]}")
        puzzle = r.content

        # These puzzles all have the same title, prefix the number so we
        # can tell them apart.
        p = puz.load(puzzle)
        orig_title = p.title
        p.title = f"[{number:02d}] {orig_title}"

        return p.tobytes()


def main():
    parser = argparse.ArgumentParser(description="fetch .puz files from Oedipus")
    parser.add_argument("number", type=int)
    args = parser.parse_args()

    downloader = PuzDownloader()
    try:
        puzzle = downloader.getPuzzle(args.number)
    except InvalidNumberException:
        print("Invalid puzzle number")
        sys.exit(1)

    # Can't just use print() here as puzzle is bytes, not a string
    with os.fdopen(sys.stdout.fileno(), "wb", closefd=False) as stdout:
        stdout.write(puzzle)
        stdout.flush()

    sys.exit(0)


if __name__ == "__main__":
    main()
