"""word.py
A program that provides functions to randomly generate words and sentences."""

# Imports

import truerandom as rand
import utils

# Constants
VOWELS = ["a", "e", "i", "o", "u"]
CONSONANTS = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"] + ["th", "wh", "ch", "sh", "ng"]
END_PUNCTUATION = [".", "?", "!"]
INSERTED_PUNCTUATION = [",", ":", ";"]

DEFAULT_SEQUENCE = [CONSONANTS, VOWELS]

SPACE = " "

# Functions
def compose_letter(seq, i):
    """Randomly choose a letter/sound according to the sequence"""
    return rand.choice(utils.loop(seq, i))

def compose_word(sounds=4, seq=DEFAULT_SEQUENCE):
    """Create a string of random letters/sounds"""
    return "".join([compose_letter(seq, i) for i in range(sounds)])

def _format_words(words):
    """Add proper formatting for words to be joined into a sentence."""
    # Capitalize the first word
    words[0] = words[0].capitalize()
    # Insert a punctuation mark somewhere in the sentence except for the last word
    try:
        words[rand.choice(range(len(words)-1))] += rand.choice(INSERTED_PUNCTUATION)
    except IndexError:
        print("You silly duck")
    # Add an ending punctuation mark to the end of the sentence
    words[-1] += rand.choice(END_PUNCTUATION)
    # Add a space to each word except for the last word
    try:
        words = [word+SPACE if word != words[-1] else word for word in words]
    except IndexError:
        # One-word sentence, do nothing
        print("You silly goose")
    return words

def _compose_words(lengths, format):
    """Generate a list of words and format if indicated"""
    words = [compose_word(sounds=l) for l in lengths]
    if format:
        words = _format_words(words)
    return words

def compose_sentence(lengths):
    """Join a list of formatted words"""
    return "".join(_compose_words(lengths, format=True))