#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
bind_pdf.py — reusable PDF re-binding (装订) script.

Reassembles pages selected from multiple source PDFs into one merged PDF,
preserving each page's MediaBox (page size) and /Rotate (visible orientation),
adding a per-page footer (output page number + source file + original page
number) and one bookmark per output page.

Dependencies
------------
* Python 3.8+ (tested on 3.14.2)
* pypdf == 7.2.0   (pure-Python; see requirements.txt)

The footer is drawn with the standard Helvetica core font (WinAnsi), so it
needs no embedded font. Footer text is rotation-aware: it is always rendered
horizontal, at the bottom of the *displayed* (visible) page, regardless of the
source page's /Rotate value. The footer is appended to each page's own content
stream (reusing that page's existing /F1 Helvetica font resource) and is
wrapped in q...Q so it cannot disturb the original content state.

Spec format (spec.json)
-----------------------
{
  "order": [
    {"file": "B.pdf", "page": 2, "bookmark": "B2"},
    ...
  ],
  "footer": "human-readable note (not rendered literally, only documented)"
}
`page` is 1-based. `bookmark` names the outline item for that output page.

Usage
-----
    .venv/bin/python outputs/bind_pdf.py \
        --spec inputs/spec.json \
        --input-dir inputs \
        --output outputs/merged.pdf \
        --page-map-csv outputs/page-map.csv \
        --page-map-json outputs/page-map.json

All paths are resolved against the current working directory; relative paths
(as shown above) work when run from the project root.
"""

import argparse
import csv
import json
import sys
from pathlib import Path

from pypdf import PdfReader, PdfWriter
from pypdf.generic import NameObject, NumberObject, TextStringObject

# Amount (in points) used to place the footer in display space.
FOOTER_LEFT_MARGIN = 36.0   # horizontal gap from the left edge of the visible page
FOOTER_BASELINE = 30.0      # distance of the text baseline above the bottom edge
FOOTER_FONT_SIZE = 9.0      # points
FOOTER_GRAY = 0.35          # non-stroking gray level (0=black, 1=white)


def footer_operations(mediabox_w: float, mediabox_h: float, rotation: int,
                      text: str) -> list:
    """Return a list of PDF content-stream operations (pypdf form) that draw
    `text` horizontally near the bottom of the *displayed* page.

    The page's /Rotate value rotates the whole page when a viewer displays it.
    We counter-rotate inside the text matrix so the footer always reads
    left-to-right at the bottom of the visible page, never sideways.
    """
    rot = int(rotation) % 360
    # Text matrix [a b c d e f].  (a,b) = direction of the text baseline in
    # page space; (c,d) = direction of glyph ascent in page space; (e,f) =
    # translation, chosen so the baseline lands at (left margin, baseline).
    if rot == 0:        # page (x,y) -> display (x,y)
        a, b, c, d, e, f = 1, 0, 0, 1, FOOTER_LEFT_MARGIN, FOOTER_BASELINE
    elif rot == 90:     # page (x,y) -> display (y, w - x)
        a, b, c, d, e, f = 0, 1, -1, 0, mediabox_w - FOOTER_BASELINE, FOOTER_LEFT_MARGIN
    elif rot == 180:    # page (x,y) -> display (w - x, h - y)
        a, b, c, d, e, f = -1, 0, 0, -1, mediabox_w - FOOTER_LEFT_MARGIN, mediabox_h - FOOTER_BASELINE
    elif rot == 270:    # page (x,y) -> display (h - y, x)
        a, b, c, d, e, f = 0, -1, 1, 0, FOOTER_BASELINE, mediabox_h - FOOTER_LEFT_MARGIN
    else:
        raise ValueError(f"unsupported /Rotate value: {rotation}")

    g = FOOTER_GRAY
    return [
        ([], b"q"),
        ([NumberObject(g), NumberObject(g), NumberObject(g)], b"rg"),
        ([], b"BT"),
        ([NameObject("/F1"), NumberObject(FOOTER_FONT_SIZE)], b"Tf"),
        ([NumberObject(v) for v in (a, b, c, d, e, f)], b"Tm"),
        ([TextStringObject(text)], b"Tj"),
        ([], b"ET"),
        ([], b"Q"),
    ]


def read_spec(spec_path: Path) -> dict:
    with spec_path.open("r", encoding="utf-8") as fh:
        spec = json.load(fh)
    if "order" not in spec or not isinstance(spec["order"], list):
        raise SystemExit(f"{spec_path}: missing 'order' list")
    return spec


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--spec", default="inputs/spec.json")
    ap.add_argument("--input-dir", default="inputs")
    ap.add_argument("--output", default="outputs/merged.pdf")
    ap.add_argument("--page-map-csv", default="outputs/page-map.csv")
    ap.add_argument("--page-map-json", default="outputs/page-map.json")
    args = ap.parse_args(argv)

    spec_path = Path(args.spec)
    input_dir = Path(args.input_dir)
    out_path = Path(args.output)
    csv_path = Path(args.page_map_csv)
    json_path = Path(args.page_map_json)

    spec = read_spec(spec_path)

    # Open each unique source file once.
    readers: dict[str, PdfReader] = {}
    for entry in spec["order"]:
        fname = entry["file"]
        if fname not in readers:
            src = input_dir / fname
            if not src.is_file():
                raise SystemExit(f"missing source PDF: {src}")
            readers[fname] = PdfReader(str(src))
        if not 1 <= int(entry["page"]) <= len(readers[fname].pages):
            raise SystemExit(
                f"{fname}: page {entry['page']} out of range "
                f"(1..{len(readers[fname].pages)})")

    writer = PdfWriter()
    page_map = []

    # 1. Copy the selected pages into the writer (size + rotation preserved).
    for entry in spec["order"]:
        fname = entry["file"]
        src_page = int(entry["page"])
        bookmark = str(entry["bookmark"])

        src_reader = readers[fname]
        page = src_reader.pages[src_page - 1]
        writer.add_page(page)

        mediabox = page.mediabox
        page_map.append({
            "output_page": len(page_map) + 1,
            "bookmark": bookmark,
            "file": fname,
            "source_page": src_page,
            "rotation": int(getattr(page, "rotation", 0) or 0),
            "mediabox_width_pt": float(mediabox.width),
            "mediabox_height_pt": float(mediabox.height),
        })

    # 2. Append the footer to every output page (in place, on the writer pages).
    for i, out_page in enumerate(writer.pages):
        info = page_map[i]
        book = info["bookmark"]
        footer = f"Page {i + 1} / {len(page_map)}  ·  {info['file']} p{info['source_page']}  [{book}]"
        info["footer_text"] = footer

        mw = info["mediabox_width_pt"]
        mh = info["mediabox_height_pt"]
        rot = info["rotation"]

        ops = footer_operations(mw, mh, rot, footer)
        content = out_page.get_contents()
        content.operations.extend(ops)
        out_page.replace_contents(content)

    # 3. Add one bookmark per output page (0-based page number).
    for i, info in enumerate(page_map):
        writer.add_outline_item(title=info["bookmark"], page_number=i)

    # 4. Write outputs.
    out_path.parent.mkdir(parents=True, exist_ok=True)
    with out_path.open("wb") as fh:
        writer.write(fh)

    _write_page_map(page_map, csv_path, json_path)

    print(f"wrote {out_path} ({len(page_map)} pages)")
    print(f"wrote {csv_path}")
    print(f"wrote {json_path}")
    for info in page_map:
        print(f"  p{info['output_page']}: {info['bookmark']} "
              f"<- {info['file']} p{info['source_page']} "
              f"(rot={info['rotation']}, {info['mediabox_width_pt']:.1f}x{info['mediabox_height_pt']:.1f})")
    return 0


def _write_page_map(page_map: list, csv_path: Path, json_path: Path) -> None:
    fields = ["output_page", "bookmark", "file", "source_page",
              "rotation", "mediabox_width_pt", "mediabox_height_pt", "footer_text"]
    csv_path.parent.mkdir(parents=True, exist_ok=True)
    with csv_path.open("w", newline="", encoding="utf-8") as fh:
        writer = csv.DictWriter(fh, fieldnames=fields)
        writer.writeheader()
        writer.writerows(page_map)

    json_path.parent.mkdir(parents=True, exist_ok=True)
    with json_path.open("w", encoding="utf-8") as fh:
        json.dump(page_map, fh, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    sys.exit(main())