from pathlib import Path
from tqdm import tqdm
import PyPDF2


def find_pdfs_with_multiple_questions(folder_path: Path):
    matching_pdfs = []

    # Use pathlib to glob for PDF files in the directory
    pdf_files = list(folder_path.glob("*.pdf"))

    # Process each PDF with a progress bar
    for pdf_file in tqdm(pdf_files, desc="Processing PDFs"):
        try:
            with pdf_file.open("rb") as file:
                reader = PyPDF2.PdfReader(file)
                text = ""
                # Extract text from each page
                for page in reader.pages:
                    page_text = page.extract_text()
                    if page_text:  # Check if text is not None
                        text += page_text
                # Check if "question" appears more than once (case-insensitive)
                if (
                    text.lower().count("question") > 1
                    and text.lower().count("find the") > 0
                ):
                    matching_pdfs.append(pdf_file.name)
                    print(pdf_file.name)
        except Exception as e:
            print(f"Error processing {pdf_file.name}: {e}")

    return matching_pdfs


if __name__ == "__main__":
    # Define the folder path using pathlib
    folder_path = Path.home() / "Downloads" / "0000"

    results = find_pdfs_with_multiple_questions(folder_path)

    print("\nPDFs containing 'question' more than once:")
    for pdf in results:
        print(pdf)
