"""Add bookmarks (a PDF outline) to a PDF: found from its text layer, or from a list you type. MIT license.

From brasspage.com/add-bookmarks-to-pdf/ (Nov 2026). Needs Python 3.10+, pypdf, and pdftotext from poppler.

Auto: python3 pdf_bookmarks.py scan-ocr.pdf out.pdf
  Reads the text layer with `pdftotext -bbox-layout`, so run OCRmyPDF on a scan first (tested with OCRmyPDF
  17.13.0). A heading is a short line (12 words or less, not ending in . , or ;) that is at least --size times the
  body text (line height or width per letter, against the median of lines with 6 words or more), with more than 1.5
  times the space above it that body lines have. Lines on the same row are joined, and a heading on 2 lines becomes
  one bookmark. Levels come from the line height: the tallest headings are level 1, and each step about 15% smaller
  is the next level (3 at most). Headings in bold at the body size, and headings in double-spaced text, are mostly
  missed: add them to the list by hand.
  It also writes out.toc.txt, the list it found, so you can fix it and run the list mode.

List: python3 pdf_bookmarks.py in.pdf out.pdf --list toc.txt
  toc.txt has one bookmark a line: page, level, title, with spaces between, for example "3 2 Statement of facts".
  Pages start at 1, level 1 is the top. Blank lines and lines that start with # are skipped. This mode reads no
  text, so the PDF needs no text layer.

pypdf copies the pages and the text layer into a new file, adds the outline, and asks the viewer to show the
bookmarks panel. Sign the PDF after you add bookmarks, not before.
Each bookmark goes to the top of its page and is set to keep the reader's zoom (/XYZ 0 top null), as California
Rules of Court rule 8.74(a)(3) asks.
"""

import argparse
import re
import statistics
import subprocess
from itertools import pairwise
from pathlib import Path
from xml.etree import ElementTree

from pypdf import PdfReader, PdfWriter
from pypdf.generic import Fit


def rows(pdf):
    """Each page's text lines as [x0, y0, x1, y1, text], top to bottom, with lines on the same row joined."""
    xml = subprocess.run(
        ["pdftotext", "-bbox-layout", pdf, "-"],
        capture_output=True,
        text=True,
        check=True,
    ).stdout
    root = ElementTree.fromstring(re.sub(r'\sxmlns="[^"]+"', "", xml, count=1))
    pages = []
    for page in root.iter("page"):
        lines = []
        for ln in page.iter("line"):
            text = " ".join(w.text for w in ln.iter("word") if w.text)
            if text:
                lines.append(
                    [float(ln.get(k)) for k in ("xMin", "yMin", "xMax", "yMax")]
                    + [text]
                )
        lines.sort(key=lambda r: (r[1], r[0]))
        out = []
        for r in lines:
            p = out[-1] if out else None
            if p and min(p[3], r[3]) - max(p[1], r[1]) > 0.5 * min(
                p[3] - p[1], r[3] - r[1]
            ):
                a, b = sorted([p, r])  # left part first
                out[-1] = [
                    min(p[0], r[0]),
                    min(p[1], r[1]),
                    max(p[2], r[2]),
                    max(p[3], r[3]),
                    a[4] + " " + b[4],
                ]
            else:
                out.append(r)
        pages.append(out)
    return pages


def find_headings(pdf, size=1.2):
    pages = rows(pdf)
    body = [
        (r[3] - r[1], (r[2] - r[0]) / len(r[4]), r[1] - q[3])
        for rs in pages
        for q, r in pairwise(rs)
        if len(r[4].split()) >= 6 and len(q[4].split()) >= 6
    ]
    if not body:
        return []
    bh, bw, bgap = (statistics.median(x) for x in zip(*body))
    found = []  # [page, height, title]
    for n, rs in enumerate(pages, 1):
        prev, group = None, None
        for r in rs:
            text, h = r[4], r[3] - r[1]
            big = (
                len(text.split()) <= 12
                and sum(c.isalpha() for c in text) >= 2
                and not text.endswith((".", ",", ";"))
                and max(h / bh, (r[2] - r[0]) / len(text) / bw) >= size
            )
            gap = r[1] - prev[3] if prev else None
            if big and group and gap < h and abs(h - group[1]) < 0.2 * group[1]:
                group[2] += " " + text  # the second line of a heading
            elif big and (gap is None or gap > 1.5 * bgap):
                group = [n, h, text]
                found.append(group)
            else:
                group = None
            prev = r
    tops = sorted({round(h, 1) for _, h, _ in found}, reverse=True)
    levels, level, top = {}, 1, tops[0] if tops else 0
    for h in tops:
        if h < 0.85 * top and level < 3:
            level, top = level + 1, h
        levels[h] = level
    return [(n, levels[round(h, 1)], title) for n, h, title in found]


def read_list(path):
    toc = []
    for line in Path(path).read_text(encoding="utf-8").splitlines():
        if line.strip() and not line.lstrip().startswith("#"):
            page, level, title = line.split(None, 2)
            toc.append((int(page), int(level), title.strip()))
    return toc


def write(src, dst, toc):
    w = PdfWriter(clone_from=PdfReader(src))
    stack = []  # (level, outline item) of the open parents
    for page, level, title in toc:
        if not 1 <= page <= len(w.pages):
            raise SystemExit(
                f"page {page} is not in {src} ({len(w.pages)} pages): {title}"
            )
        while stack and stack[-1][0] >= level:
            stack.pop()
        parent = stack[-1][1] if stack else None
        # the top of the page (the cropbox is the mediabox when not set), zoom null: the reader's zoom stays
        top = float(w.pages[page - 1].cropbox.top)
        fit = Fit.xyz(left=0, top=top, zoom=None)
        item = w.add_outline_item(
            title=title, page_number=page - 1, parent=parent, fit=fit
        )
        stack.append((level, item))
    w.page_mode = "/UseOutlines"
    with open(dst, "wb") as f:
        w.write(f)


def main():
    ap = argparse.ArgumentParser(
        description="Add bookmarks to a PDF from its text layer or from a list."
    )
    ap.add_argument("src")
    ap.add_argument("dst")
    ap.add_argument("--list", help="a list file: page level title, one bookmark a line")
    ap.add_argument(
        "--size",
        type=float,
        default=1.2,
        help="how much larger than body text a heading is (1.2)",
    )
    a = ap.parse_args()
    if a.list:
        toc = read_list(a.list)
    else:
        toc = find_headings(a.src, a.size)
        listing = Path(a.dst).with_suffix(".toc.txt")
        listing.write_text(
            "".join(f"{p} {lv} {t}\n" for p, lv, t in toc), encoding="utf-8"
        )
        print(f"{len(toc)} headings found, list in {listing}")
    write(a.src, a.dst, toc)
    print(f"{len(toc)} bookmarks written to {a.dst}")


if __name__ == "__main__":
    main()
