import random
import os

# Constants
HIGH_SCORES_FILE = 'data/high_scores.txt'
USER_DATA_FILE = 'data/user_data.txt'

# Expanded word lists
DIFFICULTY_WORDS = {
    'easy': ['cat', 'fish', 'dog', 'bird', 'frog', 'apple', 'table', 'chair', 'book', 'lamp'],
    'medium': ['giraffe', 'monkey', 'penguin', 'squirrel', 'elephant', 'dolphin', 'computer', 'pencil', 'candle', 'window'],
    'hard': ['chimpanzee', 'extraordinary', 'microorganism', 'unbelievable', 'determination', 'superintendent', 'phenomenon', 'incomprehensible', 'electromagnetic', 'characteristic']
}

# Set number of tries based on difficulty
TRIES = {
    'easy': 10,
    'medium': 7,
    'hard': 5
}

def ensure_data_directory():
    """Ensure the data directory exists."""
    if not os.path.exists('data'):
        os.makedirs('data')

def load_user_data():
    """Load user data from a file."""
    if not os.path.exists(USER_DATA_FILE):
        return {}
    
    with open(USER_DATA_FILE, 'r') as file:
        user_data = {}
        for line in file:
            username = line.strip()
            user_data[username] = True  # Using a dictionary to track registered users
        return user_data

def register_user(username):
    """Register a new user."""
    with open(USER_DATA_FILE, 'a') as file:
        file.write(username + '\n')

def user_login():
    """Handle user login or registration."""
    user_data = load_user_data()
    
    while True:
        choice = input("Login (l) or Register (r): ").lower()
        username = input("Enter your username: ").strip()

        if choice == 'l':
            if username in user_data:
                print(f"Welcome back, {username}!")
                return username
            else:
                print("Username does not exist. Please register.")
        
        elif choice == 'r':
            if username not in user_data:
                register_user(username)
                print(f"User {username} registered successfully!")
                return username
            else:
                print("Username already exists. Please choose a different one.")
        else:
            print("Invalid choice. Please enter 'l' for Login or 'r' for Register.")

def load_high_scores():
    """Load high scores from a file."""
    if not os.path.exists(HIGH_SCORES_FILE):
        return {}
    
    with open(HIGH_SCORES_FILE, 'r') as file:
        high_scores = {}
        for line in file:
            difficulty, name, score = line.strip().split(',')
            high_scores[difficulty] = (name, int(score))
        return high_scores

def save_high_score(name, score, difficulty):
    """Save player's name and score to a file."""
    ensure_data_directory()  # Ensure data directory exists
    with open(HIGH_SCORES_FILE, 'a') as file:
        file.write(f"{difficulty},{name},{score}\n")

def get_word(difficulty):
    """Select a random word from a given difficulty level."""
    return random.choice(DIFFICULTY_WORDS[difficulty])

def display_progress(selected_word, guessed_letters):
    """Display the current state of the guessed word."""
    display_word = ''
    for letter in selected_word:
        if letter in guessed_letters:
            display_word += letter + ' '
        else:
            display_word += '_ '
    print("\nCurrent word:", display_word.strip())

def guess_the_word(username):
    """Main function to run the guess the word game."""
    while True:  # Adding the loop for playing again
        print("Welcome to 'Guess the Word'!")
        difficulty = input("Choose difficulty (easy, medium, hard): ").lower()
        
        if difficulty not in DIFFICULTY_WORDS:
            print("Invalid difficulty. Please try again.")
            continue

        selected_word = get_word(difficulty)
        guessed_letters = []
        score = 100
        remaining_tries = TRIES[difficulty]  # Set tries based on selected difficulty

        while remaining_tries > 0:
            display_progress(selected_word, guessed_letters)
            print(f"Remaining tries: {remaining_tries}")
            guess = input("Guess a letter: ").lower()

            if guess in guessed_letters:
                print("You've already guessed that letter!")
                continue

            guessed_letters.append(guess)

            if guess in selected_word:
                print("Good guess!")
            else:
                remaining_tries -= 1  # Deduct one attempt for incorrect guess
                score -= 10
                print("Wrong guess! -10 points")

            if all(letter in guessed_letters for letter in selected_word):
                print(f"You guessed the word '{selected_word}'! Congratulations!")
                break
            
            if remaining_tries <= 0:
                print(f"Game over! The correct word was '{selected_word}'.")
                break

        save_high_score(username, score, difficulty)

        # Asking the player if they want to play again
        play_again = input("Do you wish to play again? (yes/no): ").lower()
        if play_again != 'yes':
            break  # Exit the loop to stop the game

# Load high scores at the start
high_scores = load_high_scores()

# Load users and handle login/registration
username = user_login()

# Display high scores if available
for difficulty in DIFFICULTY_WORDS.keys():
    if difficulty in high_scores:
        name, score = high_scores[difficulty]
        print(f"High Score [Difficulty: {difficulty}]: {name} with {score} points")

if __name__ == "__main__":
    guess_the_word(username) can you add this into this code Easy: 4-5 letter words
o Medium: 6-7 letter words
o Hard: 8+ letter words
• Guessed letters are displayed.
• Progress is displayed in the form of a console graphic i.e. Beat the shark, a race between a player and CPU.
• Scoring system – every player starts on 100 points and for each incorrect guess, 10 points are deducted. If a
player does not guess the word, they receive 0 points.
o High scores need to be saved for each difficulty AND saved between sessions along with the high
score player’s name. High Scores need to be readily accessible without having to play the game