import argparse
import logging

from qz.quality import is_valid_question
from qz.question_generator import QuestionGenerator
from qz.text_extractor import TextExtractor


def generate_questions(text: str, num_questions: int) -> list:
    generator = QuestionGenerator()
    questions = []
    attempts = 0
    max_attempts = num_questions * 2

    while len(questions) < num_questions and attempts < max_attempts:
        question_data = generator.create_quiz_question(text)
        if is_valid_question(
            question_data["text"], question_data["options"], question_data["correct_answer"]
        ):
            questions.append(question_data)
        attempts += 1

    return questions


def main():
    # Set up argument parser
    parser = argparse.ArgumentParser(description="Generate a quiz from a PDF file.")
    parser.add_argument("pdf_path", type=str, help="Path to the PDF file")
    parser.add_argument(
        "--num_questions",
        type=int,
        default=5,
        help="Number of questions to generate (default: 5)",
    )
    parser.add_argument(
        "--batch_size",
        type=int,
        default=4,
        help="Number of questions to process in parallel (default: 4)",
    )

    # Parse arguments
    args = parser.parse_args()

    try:
        # Extract text from PDF
        text_extractor = TextExtractor()
        text = text_extractor.extract_text_from_pdf(args.pdf_path)

        # Generate quiz questions
        quiz = generate_questions(text, args.num_questions)

        # Display the quiz
        for i, question in enumerate(quiz):
            print(f"Question {i + 1}: {question['text']}")
            print(f"Options: {question['options']}")
            print(f"Correct Answer: {question['options'][question['correct_answer']]}")
            print()
    except FileNotFoundError as e:
        logging.error("File not found: %s", str(e))
    except ValueError as e:
        logging.error("Invalid input: %s", str(e))
    except Exception as e:
        logging.error("Unexpected error: %s", str(e))
        raise


if __name__ == "__main__":
    main()
