"""
Shared helpers for the Workshop Document PDF scripts (ocr.py, redact.py).

Coordinates: everything that leaves these scripts is in PDF points, origin at the top-left of the
page as it is displayed (crop box, after /Rotate), y pointing down. That is what PDF.js gives at
scale 1, so the browser can position boxes without knowing about rotation. PyMuPDF's text and
redaction calls work on the unrotated page, so convert with to_display() / to_page().

These scripts never print, log or raise with document text in the message: PHP passes their
errors back to the browser.
"""

import json
import os
import sys

import pymupdf

# Tight glyph boxes (font size tall rather than ascender to descender), so word boxes on
# adjacent lines don't overlap in the browser.
pymupdf.TOOLS.set_small_glyph_heights(True)

FLAT = "flat"
DIGITAL = "digital"

OCR_DPI = 300
OCR_LANGUAGE = "eng"

TESSDATA_DIRS = [
    "/usr/share/tesseract-ocr/5/tessdata",
    "/usr/share/tesseract-ocr/4.00/tessdata",
    "/usr/share/tessdata",
    "/opt/homebrew/share/tessdata",
    "/usr/local/share/tessdata",
]


class UserError(Exception):
    """A failure the user can act on. The message must not contain document text."""


def fail(message, **extra):
    print(json.dumps({"status": "error", "message": message, **extra}))
    sys.exit(1)


def run(main):
    """Run main() and turn any failure into a JSON error without leaking document text."""
    try:
        main()
    except UserError as e:
        fail(str(e))
    except Exception as e:  # noqa: BLE001 -- the type is safe to report, the message may not be
        fail(f"The PDF could not be processed ({type(e).__name__}).")


def tessdata():
    """Tesseract's data folder. PyMuPDF only looks in TESSDATA_PREFIX and the PATH, and Apache's
    PATH often lacks the Tesseract install."""
    if os.environ.get("TESSDATA_PREFIX"):
        return os.environ["TESSDATA_PREFIX"]
    for path in TESSDATA_DIRS:
        if os.path.isfile(os.path.join(path, f"{OCR_LANGUAGE}.traineddata")):
            return path
    return None


def open_pdf(path):
    try:
        doc = pymupdf.open(path)
    except Exception:
        raise UserError("That file isn't a PDF that can be opened.")
    if not doc.is_pdf:
        raise UserError("That file isn't a PDF.")
    if doc.needs_pass:
        raise UserError("Password-protected PDFs aren't supported. Remove the password and upload it again.")
    if doc.page_count == 0:
        raise UserError("That PDF has no pages.")
    return doc


def to_display(page, rect):
    return pymupdf.Rect(rect) * page.rotation_matrix


def to_page(page, rect):
    return pymupdf.Rect(rect) * page.derotation_matrix


def visible_text_count(page):
    """Characters drawn visibly. Scans that carry an OCR text layer draw it invisibly (render
    mode 3), and those pages still need treating as flat: the pixels hold the data."""
    count = 0
    for span in page.get_texttrace():
        if span["type"] != 3 and span["opacity"] > 0:
            count += sum(1 for c in span["chars"] if chr(c[0]).strip())
    return count


def page_kind(page):
    return DIGITAL if visible_text_count(page) > 0 else FLAT


def ocr_textpage(page):
    """The page's text: its own text layer when it has one (even invisible), OCR otherwise."""
    if page.get_text("words"):
        return page.get_textpage()
    return ocr_textpage_forced(page)


def ocr_textpage_forced(page):
    try:
        return page.get_textpage_ocr(dpi=OCR_DPI, full=True, language=OCR_LANGUAGE, tessdata=tessdata())
    except Exception:
        raise UserError("OCR isn't available on the server (Tesseract or its English data is missing).")


def textpage_for(page, kind):
    return page.get_textpage() if kind == DIGITAL else ocr_textpage(page)


def words(page, textpage):
    """Word boxes in display coordinates, with block/line numbers so the browser can tell which
    words share a line."""
    out = []
    for x0, y0, x1, y1, text, block, line, _ in page.get_text("words", textpage=textpage, sort=True):
        if not text.strip():
            continue
        r = to_display(page, (x0, y0, x1, y1))
        out.append({
            "bbox": [round(v, 2) for v in (r.x0, r.y0, r.x1, r.y1)],
            "text": text,
            "line": f"{block}.{line}",
        })
    return out
