"""Inspect local PDF text and image-occurrence records; no OCR or uploads."""

import argparse
import json
from pathlib import Path
import sys

import pymupdf


def inspect_pdf(path):
    path = Path(path)
    if not path.is_file():
        raise ValueError("Input is not an existing local file")
    rows = []
    with pymupdf.open(path) as document:
        if not document.is_pdf:
            raise ValueError("Input is not a PDF")
        if document.needs_pass:
            raise ValueError("PDF requires a password; this tool does not unlock it")
        if document.page_count == 0:
            raise ValueError("PDF has no pages")
        for number, page in enumerate(document, 1):
            text = page.get_text().strip()
            rows.append({
                "page": number,
                "text_chars": len(text),
                "image_occurrences": len(page.get_image_info()),
                "text_preview": " ".join(text.split())[:100],
                "hint": "text_found" if text else "no_extracted_text",
            })
    return rows


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("pdf", help="Path to a local PDF")
    args = parser.parse_args()
    try:
        rows = inspect_pdf(args.pdf)
    except (OSError, RuntimeError, ValueError) as error:
        print(f"error: cannot inspect PDF: {error}", file=sys.stderr)
        return 2
    for row in rows:
        print(json.dumps(row, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
