#!/usr/bin/env python3
import urllib.request
import sys
from pathlib import Path
import random

URL = "https://github.com/first20hours/google-10000-english/raw/master/google-10000-english.txt"
cache = Path("first20hours.o")
if not cache.is_file():
    cache.write_bytes(urllib.request.urlopen(URL).read())
words = cache.read_text().split()

if len(sys.argv) > 1 and sys.argv[0].startswith("-"):
    print(f"Usage: {sys.argv[0]} words_number words_total is_single line_width")
    sys.exit(1)
words_number = 20 if len(sys.argv) <= 1 else int(sys.argv[1])
words_total = 300 if len(sys.argv) <= 2 else int(sys.argv[2])
is_single = True if len(sys.argv) <= 3 else eval(sys.argv[3])
line_width = 60 if len(sys.argv) <= 4 else int(sys.argv[4])

vocabulary = random.sample(words, words_number)
if is_single:
    text = random.choices(vocabulary, [words_number // 5] + [1] * (words_number - 1), k=words_total)
else:
    swap = {vocabulary[0]: vocabulary[1], vocabulary[1]: vocabulary[0]}
    text = random.choices(vocabulary, [words_number // 5] + [1] * (words_number - 1), k=words_total // 2)
    text += [swap.get(s, s) for s in text]
s = ""
for w in text:
    if len(s) > line_width:
        print(s)
        s = w
    else:
        s += " " + w
if s:
    print(s)
print()
