#!/usr/bin/env python3
# hangman - hangman game in the terminal
# Usage: hangman [--word WORD] [--auto]  (guess one letter at a time)
import argparse, random, sys

WORDS = ["python", "hangman", "computer", "keyboard", "program", "terminal", "fortune",
         "puzzle", "galaxy", "mystery", "journey", "lantern", "castle", "rocket",
         "banana", "guitar", "penguin", "volcano", "library", "rainbow"]
STAGES = [
 """
  +---+
  |   |
      |
      |
      |
      |
=========""",
 """
  +---+
  |   |
  O   |
      |
      |
      |
=========""",
 """
  +---+
  |   |
  O   |
  |   |
      |
      |
=========""",
 """
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========""",
 """
  +---+
  |   |
  O   |
 /|\\  |
      |
      |
=========""",
 """
  +---+
  |   |
  O   |
 /|\\  |
 /    |
      |
=========""",
 """
  +---+
  |   |
  O   |
 /|\\  |
 / \\  |
      |
=========""",
]
# Frequency-ordered guesses for --auto play
FREQ = "etaoinshrdlcumwfgypbvkjxqz"

def play(word, guesses=None, verbose=True):
    word = word.lower()
    guessed, wrong = set(), set()
    guess_iter = iter(guesses) if guesses is not None else None
    while True:
        shown = " ".join(c if c in guessed else "_" for c in word)
        if verbose:
            print(STAGES[len(wrong)])
            print("Word: " + shown)
            print("Wrong: " + (", ".join(sorted(wrong)) or "-"))
        if all(c in guessed for c in word):
            if verbose:
                print(f"You win! The word was '{word}'.")
            return True
        if len(wrong) >= len(STAGES) - 1:
            if verbose:
                print(STAGES[-1])
                print(f"Game over! The word was '{word}'.")
            return False
        if guess_iter is not None:
            try:
                g = next(guess_iter)
            except StopIteration:
                g = next((c for c in FREQ if c not in guessed and c not in wrong), None)
                if g is None:
                    return False
            print(f"  (auto guess: {g})") if verbose else None
        else:
            try:
                g = input("Guess a letter: ").strip().lower()
            except EOFError:
                print("\nAborted."); return False
        if len(g) != 1 or not g.isalpha():
            print("Enter a single letter."); continue
        if g in guessed or g in wrong:
            print("Already guessed that."); continue
        if g in word:
            guessed.add(g); print("Good guess!")
        else:
            wrong.add(g); print("Nope.")

def selftest():
    assert play("cat", guesses=list("cat")) is True
    assert play("zzz", guesses=list("etaoinshrdlc")) is False
    # Scripted correct guesses always win; frequency-order auto play is
    # honest gameplay and may lose (e.g. "python" needs 6 wrong guesses first).
    assert play("python", guesses=list("python")) is True
    assert play("banana", guesses=list("ban")) is True
    print("hangman selftest OK")

def main():
    p = argparse.ArgumentParser(description="Hangman game in the terminal.")
    p.add_argument("--word", default=None, help="word to guess (default: random)")
    p.add_argument("--seed", type=int, default=None, help="seed for the random word")
    p.add_argument("--auto", action="store_true", help="non-interactive: guess in frequency order")
    p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
    a = p.parse_args()
    if a.selftest:
        selftest(); return 0
    word = a.word or random.Random(a.seed).choice(WORDS)
    guesses = list(FREQ) if a.auto else None
    ok = play(word, guesses=guesses)
    return 0 if ok else 1

if __name__ == "__main__":
    sys.exit(main())
