import time
import json
import os
import random
from datetime import datetime

# Comprehensive Academic Corpus
CORPUS = {
    "Linguistics": [
        "Phonology is the study of how sounds are organized and used in natural languages.",
        "The Sapir-Whorf hypothesis suggests that the structure of a language affects its speakers' world view.",
        "Morphology is the study of words, how they are formed, and their relationship to other words."
    ],
    "Math": [
        "Euler's identity is often cited as the most beautiful equation in mathematics.",
        "A Taylor series is an expansion of a functional into an infinite sum of terms.",
        "The Fibonacci sequence is a series where each number is the sum of the two preceding ones."
    ],
    "Physics": [
        "The Heisenberg Uncertainty Principle states that position and momentum cannot both be known exactly.",
        "Special relativity posits that the laws of physics are invariant in all inertial frames.",
        "Thermodynamics deals with heat, work, and temperature, and their relation to energy."
    ],
    "Chemistry": [
        "Stoichiometry is the calculation of reactants and products in chemical reactions.",
        "The Pauli Exclusion Principle states that no two electrons can have the same four quantum numbers.",
        "Electronegativity is a measure of the tendency of an atom to attract a bonding pair of electrons."
    ],
    "Biology": [
        "The central dogma of molecular biology explains the flow of genetic information from DNA to RNA.",
        "Homeostasis is the state of steady internal physical and chemical conditions maintained by living systems.",
        "The Krebs cycle is a series of chemical reactions used by all aerobic organisms to generate energy."
    ],
    "Psychology": [
        "The Big Five personality traits are openness, conscientiousness, extraversion, agreeableness, and neuroticism.",
        "Neuroplasticity is the ability of the brain to undergo biological changes throughout an individual's life.",
        "Maslow's hierarchy of needs is a theory of psychological health predicated on fulfilling innate human needs."
    ],
    "Sociology": [
        "Social capital refers to the networks of relationships among people who live and work in a particular society.",
        "The panopticon is a type of institutional building designed to allow all inmates to be observed.",
        "Intersectionality is an analytical framework for understanding how aspects of a person's social identities combine."
    ],
    "Theology": [
        "The ontological argument is a philosophical proof for the existence of God based on the concept of being.",
        "Soteriology is the branch of religious study concerned with the doctrine of salvation.",
        "Theodicy is the vindication of divine goodness and providence in view of the existence of evil."
    ]
}

LB_FILE = "academic_leaderboard.json"

def get_leaderboard():
    if os.path.exists(LB_FILE):
        with open(LB_FILE, "r") as f:
            return json.load(f)
    return {topic: [] for topic in CORPUS.keys()}

def save_result(topic, wpm, acc):
    lb = get_leaderboard()
    lb[topic].append({"wpm": wpm, "acc": acc, "date": datetime.now().strftime("%Y-%m-%d")})
    lb[topic] = sorted(lb[topic], key=lambda x: x['wpm'], reverse=True)[:5]
    with open(LB_FILE, "w") as f:
        json.dump(lb, f, indent=4)

def run_test():
    print("\n--- ACADEMIC TYPING DOMAINS ---")
    topics = list(CORPUS.keys())
    for idx, t in enumerate(topics, 1):
        print(f"{idx}. {t}")
    
    try:
        choice = int(input("\nSelect a number to begin: ")) - 1
        topic = topics[choice]
    except (ValueError, IndexError):
        print("Invalid selection.")
        return

    prompt = random.choice(CORPUS[topic])
    print(f"\n[{topic.upper()}]")
    print(f"PROMPT: {prompt}")
    input("\nPress ENTER when ready...")

    start_t = time.time()
    attempt = input("TYPE: ")
    end_t = time.time()

    # Metrics
    duration = end_t - start_t
    wpm = round((len(attempt) / 5) / (duration / 60), 2)
    
    # Accuracy Logic: Character by character comparison
    matches = sum(1 for a, b in zip(prompt, attempt) if a == b)
    accuracy = round((matches / len(prompt)) * 100, 2)

    print(f"\n>> {wpm} WPM | {accuracy}% Accuracy")
    
    if accuracy > 80:
        save_result(topic, wpm, accuracy)
        print("High accuracy achieved! Score recorded.")
    else:
        print("Accuracy too low (<80%) to record on leaderboard.")

if __name__ == "__main__":
    while True:
        run_test()
        if input("\nAnother round? (y/n): ").lower() != 'y':
            break
