from unittest.mock import patch

from reportlab.pdfgen import canvas

from qz.main import main


def test_main_successful_execution(capsys, tmp_path):
    mock_quiz = [{"text": "Test question?", "options": ["correct", "wrong"], "correct_answer": 0}]

    # Create a valid PDF file
    test_pdf = tmp_path / "test.pdf"
    c = canvas.Canvas(str(test_pdf))
    c.drawString(100, 750, "This is a test PDF document.")
    c.save()

    with (
        patch("argparse.ArgumentParser.parse_args") as mock_args,
        patch("qz.text_extractor.TextExtractor.extract_text_from_pdf", return_value="Test content"),
        patch("qz.main.generate_questions", return_value=mock_quiz),
    ):
        # Configure arguments
        mock_args.return_value.pdf_path = str(test_pdf)
        mock_args.return_value.num_questions = 1
        mock_args.return_value.batch_size = 1

        # Run main
        main()

        # Verify output
        captured = capsys.readouterr()
        assert "Test question?" in captured.out
        assert "correct" in captured.out


def test_main_file_not_found():
    with (
        patch("argparse.ArgumentParser.parse_args") as mock_args,
        patch("qz.pdf_extractor.PDFExtractor") as mock_extractor,
        patch("logging.error") as mock_error,
    ):
        mock_args.return_value.pdf_path = "nonexistent.pdf"
        mock_extractor.return_value.generate_quiz.side_effect = FileNotFoundError()

        main()
        mock_error.assert_called_once()
