#!/usr/bin/env python3
"""why-not-searchable.py: why Ctrl+F or copy fails in a PDF, page by page, and the one OCRmyPDF command that fixes it.
MIT License, Brasspage 2026. Needs Python 3.9+ and the Poppler tools (pdfinfo, pdffonts, pdftotext, pdfimages, pdftoppm).
Usage: python3 why-not-searchable.py file.pdf
These are simple guesses, not proof. The "broken map" test expects a language in Latin letters, and an OCR layer
that reads well looks the same to this script as one that misses words.
"""

import re
import subprocess
import sys


def run(*args):
    return subprocess.run(args, capture_output=True, text=True, errors="replace")


pdf = sys.argv[1]
info = run("pdfinfo", pdf)
if info.returncode:
    sys.exit(info.stderr.strip() or "pdfinfo cannot open this file")
if re.search(r"Encrypted:\s+yes.*copy:no", info.stdout):
    fonts = len(run("pdffonts", pdf).stdout.splitlines()) - 2
    print(f"copying is turned off by the author (the file {'has' if fonts > 0 else 'has no'} text fonts)")
    sys.exit("fix: ask the author for a copy without the restriction")
n = int(re.search(r"Pages:\s+(\d+)", info.stdout)[1])
sizes = re.findall(r"Page\s+\d+ size:\s+([\d.]+) x ([\d.]+)", run("pdfinfo", "-f", "1", "-l", str(n), pdf).stdout)
area = [float(w) * float(h) for w, h in sizes]
share = [0.0] * n  # the largest picture on each page, as a share of the page area
for line in run("pdfimages", "-list", pdf).stdout.splitlines()[2:]:
    c = line.split()
    if c[2] == "image" and float(c[12]) > 0:
        p = int(c[0]) - 1
        share[p] = max(share[p], int(c[3]) * int(c[4]) * 72 * 72 / float(c[12]) / float(c[13]) / area[p])


def broken(text):
    if "�" in text or re.search(r"[\x00-\x08\x0e-\x1f]", text):
        return True
    words = re.findall(r"[^\W\d_]{2,}", text)
    return len(words) < 3 or sum(bool(re.search("[aeiouyAEIOUY]", w)) for w in words) < 0.7 * len(words)


def ink(page):  # share of dark pixels in a 36 dpi gray render (a PGM file on stdout)
    px = subprocess.run(
        ["pdftoppm", "-r", "36", "-gray", "-f", str(page), "-l", str(page), pdf], capture_output=True
    ).stdout
    w, h = map(int, px.split(b"\n")[1].split())
    return sum(b < 160 for b in px[-w * h :]) / (w * h)


WHY = {
    "scan": ("scanned page: a page-size picture and no text layer", "ocrmypdf"),
    "paths": ("text drawn as shapes (outlines), no text layer", "ocrmypdf"),
    "map": ("text with a broken font map: copy gives gibberish", "ocrmypdf --force-ocr"),
    "ocr": (
        "a text layer over a page-size picture (an OCR layer); if search misses words, redo it",
        "ocrmypdf --force-ocr --deskew",
    ),
    "pic": ("real text plus a picture; words inside the picture cannot be found", "ocrmypdf --redo-ocr"),
    "ok": ("searchable text", None),
    "blank": ("blank page", None),
}
causes = []
for p in range(1, n + 1):
    text = run("pdftotext", "-f", str(p), "-l", str(p), pdf, "-").stdout
    big = share[p - 1] > 0.5
    if not text.strip():
        cause = "scan" if big else "paths" if ink(p) > 0.002 else "blank"
    else:
        cause = "map" if broken(text) else "ocr" if big else "pic" if share[p - 1] > 0.02 else "ok"
    causes.append(cause)
    print(f"page {p}: {WHY[cause][0]}")
fixes = {WHY[c][1] for c in causes} - {None}
order = ["ocrmypdf --force-ocr --deskew", "ocrmypdf --force-ocr", "ocrmypdf --redo-ocr"]
fix = next((f for f in order if f in fixes), None)
if not fix and fixes:
    fix = "ocrmypdf --skip-text" if "ok" in causes else "ocrmypdf"  # plain ocrmypdf stops at a page that has text
print(f"fix: {fix} '{pdf}' searchable.pdf" if fix else "fix: none needed, search should work")
