#!/usr/bin/python
import string, sys, os, random, time

# seed random number generator
random.seed(os.getpid() * time.time())

def pickone(choices):
  """Select a random item from a list"""
  return choices[random.randrange(len(choices))].split()

def find_key(dict, wordlist):
  """Return the index of the first word in wordlist that is a key in dict"""
  for i in range(len(wordlist)):
    if dict.has_key(wordlist[i]):
      return i
  return None

def generate_phrase(words):
  """Recursively process a list of words, expanding the dictionary keys into
  randomly-selected replacement phrases"""

  if len(words) == 0: return []

  i = find_key(repl, words)
  try:
    left = words[:i]
    choices = repl[words[i]]
    right = words[i+1:]
    return left + generate_phrase(pickone(choices) + right)
  except:  # it didn't work
    return words

def load_data(filename="/home/each/python/foods"):
  global sentence, repl

  data = open(filename).read().splitlines()
  sentence = data.pop(0)
  repl = {}

  for line in data:
    line = line.split(":")
    for i in range(len(line)):
      line[i] = line[i].strip()    # strip whitespace
    repl[line.pop(0)] = line       # store replacement phrases in dictionary

# CGI/HTML helper functions
def printContentType(type="text/html"):
  print "Content-type:", type + "\n"

def printDocType(fp=sys.stdout):
  fp.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">\n')

def printHeaders(title="unknown", fp=sys.stdout):
  fp.write("<html><head>\n")
  fp.write("<title>"+title+"</title>\n")
  fp.write("</head>\n")
  fp.write('<body bgcolor="#ffffff">\n')

def startList(header=None, fp=sys.stdout):
  if header:
    fp.write("<h4>" + header + ":</h4>\n")
  fp.write("<ul>\n")

def bulletItem(item, fp=sys.stdout):
  fp.write("<li>" + item + "\n")

def endList(fp=sys.stdout):
  fp.write("</ul>")

def printFooter(fp=sys.stdout):
  fp.write("</body></html>\n")


#
# main
#

# load data file
load_data()

# generate HTML
printContentType()
printHeaders("Potluck menu")

startList("This week's potluck will feature")
for i in range(5):
  food = string.join(generate_phrase(sentence.split()))
  bulletItem(food[0].upper() + food[1:])
endList()

printFooter()
