# Quizbase - Universal Quiz System

Quizbase is a comprehensive quiz system that supports multiple question types, sequential/random ordering, and wrong answer collection.

## Features

- **Multiple Question Types**: Support for multiple choice, fill in the blank, true/false, and essay questions
- **JSON Data Format**: Simple and flexible JSON structure for quiz data
- **Flexible Ordering**: Sequential or random question order
- **Wrong Answer Collection**: Automatically collect and save incorrect answers
- **Progress Tracking**: Detailed statistics and session summaries
- **Type-Safe**: Built with dataclasses for type safety and IDE support

## Question Types

### Multiple Choice Questions

Single or multiple correct answers with customizable point values.

```json
{
  "question_id": "mc1",
  "question_type": "multiple_choice",
  "question_text": "What is the capital of France?",
  "options": ["London", "Paris", "Berlin", "Rome"],
  "correct_answer": 1,
  "allow_multiple": false,
  "points": 1.0
}
```

### Fill in the Blank Questions

Case-sensitive or case-insensitive with multiple valid answers.

```json
{
  "question_id": "fb1",
  "question_type": "fill_blank",
  "question_text": "The planet closest to the Sun is _____.",
  "correct_answers": ["Mercury"],
  "case_sensitive": false,
  "points": 1.0
}
```

### True/False Questions

Simple boolean questions with flexible input format.

```json
{
  "question_id": "tf1",
  "question_type": "true_false",
  "question_text": "Python is a compiled language.",
  "correct_answer": false,
  "points": 1.0
}
```

### Essay Questions

Keyword-based validation with model answers for comparison.

```json
{
  "question_id": "es1",
  "question_type": "essay",
  "question_text": "Explain the concept of object-oriented programming.",
  "model_answer": "Object-oriented programming (OOP) is...",
  "keywords": ["objects", "classes", "inheritance", "encapsulation"],
  "points": 5.0
}
```

## Installation

Quizbase is part of the pytola project. Install from source:

```bash
cd pytola/quizbase
pip install -e .
```

## Usage

### Command Line Interface

```bash
# Create a sample quiz data file
quizbase --create-sample

# Run quiz with sequential order
quizbase --file quiz.json

# Run quiz with random order
quizbase --file quiz.json --random

# Run quiz and save wrong answers to custom file
quizbase --file quiz.json --wrong my_mistakes.json
```

## GUI Version

Quizbase also provides a PySide2-based graphical user interface for an enhanced user experience.

### Installation

The GUI version requires PySide2:

```bash
# Install with GUI support
pip install pytola[gui]

# Or install PySide2 separately
pip install PySide2>=5.15.2.1
```

### Launching the GUI

```bash
# Launch GUI application
quizbase-gui

# Alternative command
quiz-gui
```

### GUI Features

- **Visual Interface**: Clean and intuitive user interface
- **Multiple Choice Support**: Radio buttons for single choice, checkboxes for multiple choice
- **Text Input**: Text fields for fill-in-the-blank questions
- **True/False**: Dedicated radio buttons for boolean questions
- **Essay Support**: Rich text editor for essay questions
- **Progress Tracking**: Real-time progress and score display
- **Statistics Tab**: Detailed quiz summary and question breakdown
- **Wrong Answers Review**: Dedicated tab to review incorrect answers
- **Recent Files**: Quick access to recently opened quiz files
- **Random Order**: Toggle between sequential and random question order
- **Configuration Persistence**: Window settings and preferences saved automatically
- **Sample Quiz Generation**: Built-in sample quiz creation

### GUI Workflow

1. **Load Quiz**: Click "Open Quiz File" to load a JSON quiz file
2. **Create Sample**: Click "Create Sample" to generate a sample quiz
3. **Answer Questions**:
   - Read the question
   - Select or type your answer
   - Click "Submit Answer"
   - Review the feedback
4. **Navigate**:
   - Click "Next Question" to continue
   - Or use "Finish Quiz" to complete early
5. **Review Results**:
   - Switch to "Summary" tab for detailed statistics
   - Check "Wrong Answers" tab for incorrect responses
6. **Reset**: Click "Reset Quiz" to start over

### GUI Screenshots

The GUI includes three main tabs:

- **Quiz Tab**: Answer questions with instant feedback
- **Summary Tab**: View detailed statistics and question-by-question breakdown
- **Wrong Answers Tab**: Review and analyze incorrect answers

### Configuration

The GUI stores configuration in `~/.pytola/quizbase_gui.json`:

```json
{
  "window_width": 1000,
  "window_height": 700,
  "window_x": 100,
  "window_y": 100,
  "random_order": false,
  "wrong_answers_file": "wrong_answers.json",
  "recent_files": []
}
```

### Programmatic GUI Usage

You can also integrate the GUI components into your own applications:

```python
from pytola.office.quizbase.quizbase_gui import QuizBaseMainWindow
from PySide2.QtWidgets import QApplication
import sys

app = QApplication(sys.argv)
window = QuizBaseMainWindow()
window.show()
sys.exit(app.exec_())
```

### Programmatic Usage

```python
from pytola.office.quizbase.quizbase import QuizSession

# Create quiz session
session = QuizSession(random_order=True)
session.load_from_json("quiz.json")

# Answer questions
while not session.is_finished():
    question = session.get_current_question()
    print(question.question_text)

    answer = input("Your answer: ")
    result = session.submit_answer(answer)

    print(result.explanation)

# Get summary
summary = session.get_summary()
print(f"Accuracy: {summary['accuracy']:.1f}%")

# Save wrong answers
session.save_wrong_answers()
```

### Creating Custom Questions

```python
from pytola.office.quizbase.quizbase import (
    MultipleChoiceQuestion,
    QuestionType
)

# Create a multiple choice question
question = MultipleChoiceQuestion(
    question_id="custom1",
    question_type=QuestionType.MULTIPLE_CHOICE,
    question_text="What is 2+2?",
    options=["3", "4", "5"],
    correct_answer=1,
    allow_multiple=False,
    points=1.0
)

# Check answer
is_correct, explanation = question.check_answer(1)
print(explanation)  # "Correct! 4 is the right answer."
```

### Programmatic Quiz Creation

```python
from pytola.office.quizbase.quizbase import QuizSession, MultipleChoiceQuestion

# Create questions manually
questions = [
    MultipleChoiceQuestion(
        question_id="q1",
        question_type=QuestionType.MULTIPLE_CHOICE,
        question_text="What is Python?",
        options=["Language", "Library", "Tool"],
        correct_answer=0,
        allow_multiple=False,
        points=1.0
    ),
    # Add more questions...
]

# Create session with custom questions
session = QuizSession(questions=questions, random_order=False)

# Run quiz
while not session.is_finished():
    question = session.get_current_question()
    # ... interact with user ...
```

## Quiz JSON Format

Complete quiz file structure:

```json
{
  "title": "General Knowledge Quiz",
  "questions": [
    {
      "question_id": "mc1",
      "question_type": "multiple_choice",
      "question_text": "What is the capital of France?",
      "options": ["London", "Paris", "Berlin", "Rome"],
      "correct_answer": 1,
      "allow_multiple": false,
      "points": 1.0
    }
  ]
}
```

## Session Statistics

QuizSession provides detailed statistics:

```python
summary = session.get_summary()
# {
#   "total_questions": 10,
#   "answered": 8,
#   "correct": 6,
#   "wrong": 2,
#   "total_points": 20.0,
#   "earned_points": 12.0,
#   "accuracy": 75.0,
#   "is_finished": false
# }
```

## Wrong Answer Collection

Wrong answers are automatically collected and can be saved:

```python
# Get all wrong answers
wrong_answers = session.get_wrong_answers()

# Save to JSON file
session.save_wrong_answers("mistakes.json")

# Review wrong answers later
for result in wrong_answers:
    print(f"Question: {result.question.question_text}")
    print(f"Your answer: {result.user_answer}")
    print(f"Explanation: {result.explanation}")
```

## Advanced Features

### Cached Properties

The system uses `@cached_property` for efficient computation:

```python
# Statistics are computed once and cached
total = session.total_questions
correct = session.correct_count
accuracy = session.accuracy  # Cached calculation
```

### Type Safety

All data structures use dataclasses for type safety:

```python
from pytola.office.quizbase.quizbase import Question

question: Question = Question.from_dict(data)
# Full type hints and IDE support
```

## Testing

Run the test suite:

```bash
pytest pytola/quizbase/tests/
```

Run with coverage:

```bash
pytest --cov=pytola/quizbase pytola/quizbase/tests/
```

## API Reference

### Core Classes

- **Question**: Base class for all question types
- **MultipleChoiceQuestion**: Multiple choice questions
- **FillBlankQuestion**: Fill in the blank questions
- **TrueFalseQuestion**: True/false questions
- **EssayQuestion**: Essay questions with keyword validation
- **QuizSession**: Manages quiz execution and statistics
- **QuizResult**: Result of answering a question

### Enums

- **QuestionType**: Supported question types (MULTIPLE_CHOICE, FILL_BLANK, TRUE_FALSE, ESSAY)

### Functions

- **create_sample_quiz_data()**: Create sample quiz data file
- **main()**: CLI entry point

## License

Part of the pytola project. See main project license for details.
