#!/usr/bin/env python3
# typing - typing speed test in the terminal
# Usage: typing [--text TEXT] [--auto]  (type the shown text, then Enter; Ctrl-D to finish)
import argparse, random, sys, time

TEXTS = [
 "The quick brown fox jumps over the lazy dog.",
 "Pack my box with five dozen liquor jugs.",
 "First solve the problem, then write the code.",
 "Simplicity is the soul of efficiency and the mark of good design.",
 "A journey of a thousand miles begins with a single step.",
 "To be or not to be, that is the question.",
 "The best time to plant a tree was twenty years ago.",
]

def score(target, typed, elapsed):
    if elapsed <= 0:
        elapsed = 0.01
    words = len(typed.split())
    wpm = words / (elapsed / 60.0)
    correct = sum(1 for a, b in zip(target, typed) if a == b)
    total = max(len(target), len(typed), 1)
    acc = 100.0 * correct / total
    # accuracy against target length is fairer for short input
    acc_t = 100.0 * correct / max(len(target), 1)
    return wpm, acc_t

def run_interactive(text):
    print("Type the following text, then press Enter (Ctrl-D when done):")
    print()
    print("  " + text)
    print()
    start = time.time()
    try:
        typed = input("> ")
    except EOFError:
        typed = ""
    elapsed = time.time() - start
    wpm, acc = score(text, typed, elapsed)
    print(f"\nTime: {elapsed:.1f}s  Words: {len(typed.split())}  WPM: {wpm:.1f}  Accuracy: {acc:.1f}%")
    if acc >= 95 and wpm >= 40:
        print("Excellent typing!")
    elif acc >= 90:
        print("Good — keep practising for speed.")
    else:
        print("Slow down a little and aim for accuracy first.")
    return 0

def selftest():
    text = TEXTS[0]
    wpm, acc = score(text, text, 30.0)
    assert abs(wpm - 9 / 0.5) < 0.01, wpm  # 9 words in 30s = 18 wpm
    assert acc == 100.0
    wpm2, acc2 = score(text, text[:10] + "XXXX" + text[14:], 60.0)
    assert acc2 < 100.0
    print(f"typing selftest OK (perfect run: {wpm:.1f} WPM, {acc:.1f}% accuracy)")
    # scripted stdin path: --auto feeds the exact text
    return 0

def main():
    p = argparse.ArgumentParser(description="Typing speed test in the terminal.")
    p.add_argument("--text", default=None, help="text to type (default: random sample)")
    p.add_argument("--seed", type=int, default=None, help="seed for the random sample")
    p.add_argument("--auto", action="store_true", help="non-interactive demo: score a perfect run")
    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
    text = a.text or random.Random(a.seed).choice(TEXTS)
    if a.auto:
        wpm, acc = score(text, text, 30.0)
        print(f"Text: {text}")
        print(f"Auto run — Time: 30.0s  WPM: {wpm:.1f}  Accuracy: {acc:.1f}%")
        return 0
    return run_interactive(text)

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