import time
import random
import nltk
from nltk.corpus import gutenberg

# Download necessary datasets
nltk.download('gutenberg', quiet=True)
nltk.download('punkt', quiet=True)

def get_random_sentence():
    """Fetches a random sentence from the NLTK Gutenberg corpus."""
    # We'll use 'melville-moby_dick.txt' for classic practice
    sentences = gutenberg.sents('melville-moby_dick.txt')
    
    # Filter for sentences that are a reasonable length (10-25 words)
    valid_sentences = [" ".join(s) for s in sentences if 10 < len(s) < 25]
    return random.choice(valid_sentences)

def calculate_metrics(original, typed, elapsed_time):
    """Calculates WPM and Accuracy."""
    # Standard WPM formula: (Characters / 5) / Time in Minutes
    words_per_minute = (len(typed) / 5) / (elapsed_time / 60)
    
    # Simple accuracy check
    original_words = original.split()
    typed_words = typed.split()
    correct_words = sum(1 for o, t in zip(original_words, typed_words) if o == t)
    accuracy = (correct_words / len(original_words)) * 100
    
    return round(words_per_minute, 2), round(accuracy, 2)

def run_test():
    target_text = get_random_sentence()
    
    print("\n" + "="*50)
    print("PYTHON TYPING SPEED TEST (NLTK Edition)")
    print("="*50)
    print(f"\nPROMPT:\n{target_text}\n")
    
    input("Press ENTER when you are ready to start...")
    
    start_time = time.time()
    user_input = input("\nSTART TYPING:\n")
    end_time = time.time()
    
    time_taken = end_time - start_time
    wpm, accuracy = calculate_metrics(target_text, user_input, time_taken)
    
    print("\n" + "-"*20)
    print(f"RESULTS:")
    print(f"Time: {time_taken:.2f} seconds")
    print(f"Speed: {wpm} WPM")
    print(f"Accuracy: {accuracy}%")
    print("-"*20)

if __name__ == "__main__":
    while True:
        run_test()
        if input("\nTry another sentence? (y/n): ").lower() != 'y':
            print("Keep practicing!")
            break



