import argparse
from pathlib import Path
import sqlite3

from handbook_search import DEFAULT_DB, search

CASES = [
    ("Which item is EQ-314?", 2),
    ("How long may I borrow books?", 1),
    ("Where do I sign up for Workshop A?", 3),
    ("When does the reading room shut on Saturday?", 3),
    ("What if another reader has requested the book I want to renew?", 1),
    ("May I keep the novel an additional fortnight if nobody else requested it?", 1),
    ("Which station can digitize a paper photograph?", 2),
    ("Who can tell me when the next class is?", 3),
]
MODES = ("keyword", "vector", "hybrid")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Score page retrieval on the fictional handbook.")
    parser.add_argument("--db", type=Path, default=DEFAULT_DB)
    args = parser.parse_args()

    try:
        for mode in MODES:
            first = found = 0
            print(mode)
            for question, expected in CASES:
                hits = search(args.db, question, mode, limit=3)
                pages = [hit.page for hit in hits if hit.source == "library-handbook.pdf"]
                first += bool(hits and hits[0].source == "library-handbook.pdf" and hits[0].page == expected)
                found += expected in pages
                print(f"  expected {expected}; retrieved {pages or 'none'} | {question}")
            print(f"  First result: {first}/{len(CASES)} | Top three: {found}/{len(CASES)}")
    except (OSError, sqlite3.Error, ValueError) as error:
        raise SystemExit(str(error)) from None
