import sys
try:
    import fitz  # PyMuPDF
except ImportError:
    import subprocess
    subprocess.check_call([sys.executable, "-m", "pip", "install", "PyMuPDF"])
    import fitz

pdf_path = "/home/user/uploads/NEW MENTORSHIP REPORT.pdf"
doc = fitz.open(pdf_path)

# Extract text
text = ""
for page in doc:
    text += page.get_text()

with open("report_text.txt", "w", encoding="utf-8") as f:
    f.write(text)

# Extract images
import os
os.makedirs("images/report", exist_ok=True)
image_count = 0
for page_index in range(len(doc)):
    page = doc[page_index]
    image_list = page.get_images(full=True)
    
    for img_index, img in enumerate(image_list):
        xref = img[0]
        base_image = doc.extract_image(xref)
        image_bytes = base_image["image"]
        image_ext = base_image["ext"]
        
        # Only save reasonably sized images (ignore tiny icons/lines)
        if len(image_bytes) > 5000:
            image_name = f"images/report/img_p{page_index}_{img_index}.{image_ext}"
            with open(image_name, "wb") as f:
                f.write(image_bytes)
            image_count += 1

print(f"Extracted text to report_text.txt")
print(f"Extracted {image_count} images to images/report/")
