#!/usr/bin/env python3
"""Grade a Bibliome study deck yourself, and get the share of its cards that are right.

Psychosonic Lab, Experiment 10: https://psychosonicconsulting.com/lab/study-cards

1. In Bibliome on the Mac, make study cards from a chapter you know well.
2. In the deck, choose Export, then CSV. The file has five columns:
   front, back, type, page, quote.
3. Run:  python3 study-cards-check.py "My Deck.csv"

Cards come up in a random order. For each one you see the front first, so you can
answer it in your head, then the back, the quote it was written from, and its page.
Open the PDF at that page when you are unsure. Then answer three questions, the same
three this Lab's graders answered:

  right?      Is the back a true and complete answer to the front, going by the book?
  quote?      Does the quote under the card, on its own, show that answer?
  worth it?   Would you want to memorize this card?

Your answers go to "<deck>.graded.csv" after every card, so you can stop with q and
pick up later where you left off. At the end it prints the share right, with a 95%
interval, which is how wide the doubt is for that many cards.

Options:
  --sample N   grade N random cards instead of the whole deck
  --seed S     the order to use (default 10), so a second run asks in the same order

Standard library only. It reads your CSV and writes one file beside it, nothing else.
"""
import argparse
import csv
import math
import os
import random
import sys


def wilson(k, n, z=1.96):
    """A 95% interval for k right out of n. Wider when n is small."""
    if n == 0:
        return 0.0, 0.0
    p = k / n
    d = 1 + z * z / n
    c = (p + z * z / (2 * n)) / d
    w = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return max(0.0, c - w), min(1.0, c + w)


def read_deck(path):
    with open(path, newline="", encoding="utf-8-sig") as f:
        rows = list(csv.reader(f))
    if not rows:
        sys.exit("The file is empty.")
    # The first row is the header Bibliome writes, in the app's language. Columns are
    # read by position, so any language works.
    cards = []
    for i, r in enumerate(rows[1:], 1):
        if len(r) < 5:
            sys.exit(f"Row {i + 1} has {len(r)} columns; a Bibliome CSV export has 5. Is this the right file?")
        cards.append({"id": str(i), "front": r[0], "back": r[1], "type": r[2], "page": r[3], "quote": r[4]})
    return cards


def ask(prompt):
    while True:
        a = input(prompt).strip().lower()
        if a in ("y", "n", "s", "q"):
            return a
        print("   y for yes, n for no, s to skip this card, q to stop for now")


def main():
    ap = argparse.ArgumentParser(description="Grade a Bibliome study deck yourself.")
    ap.add_argument("deck", help="the CSV file Bibliome exported")
    ap.add_argument("--sample", type=int, default=0, help="grade this many random cards")
    ap.add_argument("--seed", type=int, default=10, help="the random order to use")
    a = ap.parse_args()

    cards = read_deck(a.deck)
    random.Random(a.seed).shuffle(cards)
    if a.sample:
        cards = cards[: a.sample]
    out = os.path.splitext(a.deck)[0] + ".graded.csv"
    fields = ["card", "type", "page", "right", "quote_shows_it", "worth_it"]
    done = {}
    if os.path.exists(out):
        with open(out, newline="", encoding="utf-8") as f:
            done = {r["card"]: r for r in csv.DictReader(f)}
        print(f"Picking up from {out}: {len(done)} cards already graded.")

    todo = [c for c in cards if c["id"] not in done]
    for i, c in enumerate(todo, 1):
        print(f"\n--- card {len(done) + 1} of {len(cards)} ({c['type']}, page {c['page']}) ---")
        print(f"FRONT  {c['front']}")
        input("       (Enter to show the answer) ")
        print(f"BACK   {c['back']}")
        print(f"QUOTE  {c['quote']}")
        answers = []
        for q in ("right?    ", "quote?    ", "worth it? "):
            r = ask(f"  {q}[y/n/s/q] ")
            if r in ("s", "q"):
                break
            answers.append(r)
        if r == "q":
            break
        if r == "s":
            continue
        done[c["id"]] = {"card": c["id"], "type": c["type"], "page": c["page"], "right": answers[0],
                         "quote_shows_it": answers[1], "worth_it": answers[2]}
        with open(out, "w", newline="", encoding="utf-8") as f:
            w = csv.DictWriter(f, fieldnames=fields)
            w.writeheader()
            w.writerows(done.values())

    graded = list(done.values())
    n = len(graded)
    print(f"\n{n} cards graded, saved in {out}")
    if not n:
        return
    for key, label in (("right", "right"), ("quote_shows_it", "quote shows it"), ("worth_it", "worth memorizing")):
        k = sum(1 for g in graded if g[key] == "y")
        lo, hi = wilson(k, n)
        print(f"  {label:17s} {k} of {n} = {100 * k / n:.0f}%   (95% interval {100 * lo:.0f}% to {100 * hi:.0f}%)")
    print("\nThe Lab's figures, for comparison: psychosonicconsulting.com/lab/study-cards")


if __name__ == "__main__":
    try:
        main()
    except (KeyboardInterrupt, EOFError):
        print("\nStopped. Your answers so far are saved.")
