"""Extract text from scanned/image-only PDFs using pymupdf + tesseract."""

import argparse
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import fitz  # pymupdf
import pytesseract
from PIL import Image

from output_utils import output_to_file_or_stdout


def extract(pdf_path: str, dpi: int = 300) -> list[dict]:
    """Render each page to an image and OCR it. Returns list of page dicts."""
    results = []
    with fitz.open(pdf_path) as doc:
        for i, page in enumerate(doc, start=1):
            mat = fitz.Matrix(dpi / 72, dpi / 72)
            pix = page.get_pixmap(matrix=mat)
            img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
            text = pytesseract.image_to_string(img)
            results.append({"page": i, "text": text})
            del pix  # free memory immediately
    return results


def main():
    parser = argparse.ArgumentParser(description="OCR scanned PDFs")
    parser.add_argument("pdf", help="Path to input PDF")
    parser.add_argument("output", nargs="?", default=None, help="Output file path")
    parser.add_argument("--format", choices=["txt", "json", "md"], default="txt",
                        dest="fmt", help="Output format (default: txt)")
    parser.add_argument("--dpi", type=int, default=300, help="Render DPI (default: 300)")
    args = parser.parse_args()

    pages = extract(args.pdf, dpi=args.dpi)

    if args.fmt == "json":
        data = {"extractor": "scanned", "pages": pages}
    else:
        data = pages

    output_to_file_or_stdout(data, args.fmt, args.output)


if __name__ == "__main__":
    main()
