"""Assembles a document onto three PDFs somebody else made: one behind its first
page, one behind every page in the middle, and one that goes in whole as its last
page.

The Python twin of the `write_imported_pages` example in Rust. This is what a
document server is asked for most often. The customer sends stationery — a headed
sheet, a plain continuation sheet, a page of standing conditions — and the document
has to be laid on it without any of it being redrawn. Each sheet is read, brought in
as a form, and stamped under what this example draws. The conditions sheet carries
nothing of its own but the page number, and is a counted page like the rest.

The page the schedule needs is decided by the schedule: the table is handed over
whole and says how many pages it takes, so the continuation sheet backs as many
pages as there turn out to be.

What the pack says is written in the language ``HQF_PDF_LANG`` names. What it is
about is not: the reference, the two parties, their addresses and their tax numbers,
the quantities and the prices are the same pack whichever language reads it.

The three sheets may be handed over on the command line. With none given, the
example writes them itself, so it runs on any machine.

Usage: python examples/write_imported_pages.py [out.pdf]
       [headed.pdf continuation.pdf conditions.pdf]
       HQF_PDF_LANG=fr python examples/write_imported_pages.py
"""

from __future__ import annotations

import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Callable

import _language
import _licence
import _out

import hqf_pdf

# A4, in points.
PAGE_WIDTH = 595.276
# The page's left edge and, mirrored, its right.
LEFT = 56.0
RIGHT = PAGE_WIDTH - LEFT
# The width the table is fitted across.
TABLE_WIDTH = PAGE_WIDTH - 2 * LEFT
# Where the second column of the two address blocks begins.
SECOND_COLUMN = 320.0

# The ink the headings and rules are drawn in, and the grey of the small print.
ACCENT = hqf_pdf.Rgb(0.11, 0.33, 0.55)
MUTED = hqf_pdf.Rgb(0.42, 0.42, 0.45)
INK = hqf_pdf.Rgb(0.1, 0.1, 0.12)

# The agreement this pack schedules, which no language renumbers.
REFERENCE = "SA-2027-0088"

# The supplier and the customer: what they are called, where they are, and the tax
# number each answers to. None of it is language.
SUPPLIER = "HQF Development"
SUPPLIER_STREET = "42 lot les Genêts"
SUPPLIER_TOWN = "13480 Calas, France"
SUPPLIER_VAT = "FR59 752 492 777"
CUSTOMER = "Meridian Optics SAS"
CUSTOMER_STREET = "18 avenue des Peupliers"
CUSTOMER_TOWN = "69100 Villeurbanne, France"
CUSTOMER_VAT = "FR41 512 336 908"

# The box the schedule is fitted into, on whichever page it lands.
TABLE_TOP = 780.0
TABLE_BOTTOM = 80.0


@dataclass(frozen=True)
class Words:
    """What the pack says, in one language.

    What it is about is held outside: the reference, the parties, their addresses,
    their tax numbers, the days, the quantities and the prices are the same pack in
    every language.
    """

    # What the pack is called, at the head of its front page.
    title: str
    # What stands between the reference and the day the pack was drawn up.
    drawn_up: str
    # The day it was drawn up.
    drawn_up_on: str
    # What heads each of the two address blocks.
    supplier: str
    customer: str
    # What stands before a tax number.
    vat: str
    # What heads the lines that say what the pack stands on.
    made_of: str
    # Those lines, broken where the page breaks them: what the pack stands on, then what
    # is done with it.
    stands_on: tuple[str, ...]
    stamped: tuple[str, ...]
    # What heads the list of the pack's own pages.
    in_it: str
    # What one page of the pack is called, and what several are.
    page: str
    pages: str
    # What runs between the first page of a span and its last.
    to: str
    # What runs between a page's number and how many there are.
    of: str
    # What each of the three entries of the list says.
    front_sheet: str
    schedule_before: str
    schedule_after: str
    conditions_entry: str
    # What heads the two places the parties sign, and the line under it.
    signed: str
    signed_note: str
    # What stands before the name of a party over the rule it signs on.
    for_party: str
    # What is asked for under the second rule.
    name_and_date: str
    # The four headings of the schedule.
    headings: tuple[str, ...]
    # What each batch delivers, in the order BATCHES schedules them.
    batches: tuple[str, ...]
    # The month each quarter's batches are due in, in the order YEARS runs them.
    months: tuple[str, ...]
    # What the last row of the schedule adds up.
    total: str
    # What the conditions sheet is headed, and the line at its foot.
    conditions_title: str
    conditions_edition: str
    # The standing clauses, one to a line.
    clauses: tuple[str, ...]


# The pack in English.
ENGLISH = Words(
    title="Supply agreement",
    drawn_up="drawn up",
    drawn_up_on="12 March 2027",
    supplier="Supplier",
    customer="Customer",
    vat="VAT",
    made_of="What this pack is made of",
    stands_on=(
        "This pack stands on three sheets the customer sent as PDF files. The headed"
        " sheet is under",
        "this page. A plain continuation sheet is under every page the schedule runs"
        " to. The page of",
        "standing conditions at the back is the third sheet, taken in whole and counted"
        " like the rest.",
    ),
    stamped=(
        "None of the three is redrawn. The team reads each file, brings its page in as"
        " a drawing, and",
        "stamps it under the text — so a letterhead comes out of the printer as its"
        " owner made it, and",
        "the conditions on the last page are the ones on file, to the letter.",
    ),
    in_it="What is in it",
    page="Page",
    pages="Pages",
    to="to",
    of="of",
    front_sheet="This page, on the headed sheet.",
    schedule_before="The delivery schedule, ",
    schedule_after=" rows, on the continuation sheet.",
    conditions_entry="The conditions of supply, as the customer supplied them.",
    signed="Signed",
    signed_note=(
        "Each party signs one copy. The schedule and the conditions of supply are part"
        " of it."
    ),
    for_party="For",
    name_and_date="Name and date",
    headings=("Batch", "Due", "Quantity", "Value"),
    batches=(
        "Lens blanks, 62 mm, coated",
        "Lens blanks, 68 mm, coated",
        "Lens blanks, 74 mm, uncoated",
        "Frame fronts, acetate, assorted",
        "Frame temples, acetate, pairs",
        "Hinges, sprung, stainless",
        "Nose pads, silicone",
        "Screws, M1.4, boxed by hundred",
        "Cases, hard, printed",
        "Cloths, microfibre, printed",
        "Cartons, shipping, printed",
    ),
    months=("April", "July", "October", "January"),
    total="Total, before tax",
    conditions_title="Conditions of supply",
    conditions_edition="conditions of supply, edition of 1 January 2027",
    clauses=(
        "Prices are firm for the term of this agreement, in euros, exclusive of value"
        " added tax.",
        "A batch is due on the day named in the schedule, at the address the schedule"
        " was sent to.",
        "Quantities are counted on arrival. A count that differs is settled within five"
        " working days.",
        "Payment falls thirty days after the batch arrives, by transfer to the account"
        " on the invoice.",
        "Title to a batch passes on payment. Risk passes on arrival.",
        "A batch refused on arrival is collected within ten working days, at the"
        " supplier's cost.",
        "Either party may end this agreement on ninety days' notice, in writing.",
        "Batches already scheduled at the end of the notice are supplied and paid for"
        " as scheduled.",
        "Neither party is answerable for a delay caused by an event outside its"
        " reasonable control.",
        "This agreement is governed by French law, and the courts of Aix-en-Provence"
        " hear disputes.",
        "A change to a scheduled batch takes effect only when both parties agree it in"
        " writing.",
        "The supplier keeps a certificate of conformity for each batch three years"
        " after it arrives.",
        "The customer's marks may go on cartons and cases for the term, and to no other"
        " purpose.",
        "Neither party may hand this agreement to anyone else without the other's"
        " written consent.",
        "Notices are given in writing, to the addresses printed on the first page of"
        " this pack.",
        "This pack, its schedule and these conditions are the whole of what the parties"
        " agreed.",
    ),
)

# The pack in French.
FRENCH = Words(
    title="Contrat d'approvisionnement",
    drawn_up="établi le",
    drawn_up_on="12 mars 2027",
    supplier="Fournisseur",
    customer="Client",
    vat="TVA",
    made_of="De quoi ce dossier est fait",
    stands_on=(
        "Ce dossier repose sur trois feuilles que le client a envoyées en PDF. La"
        " feuille à en-tête",
        "est sous cette page. Une feuille de suite nue est sous chaque page du"
        " calendrier. Les",
        "conditions du dos sont la troisième feuille, prise entière et comptée comme"
        " les autres.",
    ),
    stamped=(
        "Aucune des trois n'est redessinée. L'équipe lit chaque fichier, entre sa page"
        " comme un",
        "dessin, et la tamponne sous le texte — un papier à en-tête sort donc de"
        " l'imprimante tel",
        "que son propriétaire l'a fait, et les conditions du dos sont celles du"
        " fichier, à la lettre.",
    ),
    in_it="Ce qu'il contient",
    page="Page",
    pages="Pages",
    to="à",
    of="sur",
    front_sheet="Cette page, sur la feuille à en-tête.",
    schedule_before="Le calendrier de livraison, ",
    schedule_after=" lignes, sur la feuille de suite.",
    conditions_entry=(
        "Les conditions de fourniture, telles que le client les a fournies."
    ),
    signed="Signatures",
    signed_note=(
        "Chaque partie signe un exemplaire. Le calendrier et les conditions de"
        " fourniture en font partie."
    ),
    for_party="Pour",
    name_and_date="Nom et date",
    headings=("Lot", "Échéance", "Quantité", "Montant"),
    batches=(
        "Ébauches de verres, 62 mm, traitées",
        "Ébauches de verres, 68 mm, traitées",
        "Ébauches de verres, 74 mm, non traitées",
        "Faces de montures, acétate, assorties",
        "Branches de montures, acétate, paires",
        "Charnières à ressort, inox",
        "Plaquettes de nez, silicone",
        "Vis M1.4, boîtes de cent",
        "Étuis rigides, imprimés",
        "Chiffonnettes microfibre, imprimées",
        "Cartons d'expédition, imprimés",
    ),
    months=("avril", "juillet", "octobre", "janvier"),
    total="Total hors taxes",
    conditions_title="Conditions de fourniture",
    conditions_edition="conditions de fourniture, édition du 1er janvier 2027",
    clauses=(
        "Les prix sont fermes pour la durée du contrat, en euros, hors taxe sur la"
        " valeur ajoutée.",
        "Un lot est dû le jour nommé au calendrier, à l'adresse à laquelle le"
        " calendrier a été envoyé.",
        "Les quantités sont comptées à l'arrivée. Un écart de comptage se règle sous"
        " cinq jours ouvrés.",
        "Le paiement échoit trente jours après l'arrivée du lot, par virement au compte"
        " porté sur la facture.",
        "La propriété d'un lot passe au paiement. Le risque passe à l'arrivée.",
        "Un lot refusé à l'arrivée est repris sous dix jours ouvrés, aux frais du"
        " fournisseur.",
        "Chaque partie peut mettre fin au contrat avec un préavis de quatre-vingt-dix"
        " jours, par écrit.",
        "Les lots déjà inscrits au calendrier à la fin du préavis sont livrés et payés"
        " comme prévu.",
        "Aucune partie ne répond d'un retard causé par un événement échappant à son"
        " contrôle raisonnable.",
        "Le contrat est régi par le droit français, et les tribunaux d'Aix-en-Provence"
        " tranchent les litiges.",
        "Une modification d'un lot au calendrier ne prend effet que si les deux parties"
        " l'acceptent par écrit.",
        "Le fournisseur conserve un certificat de conformité par lot pendant trois ans"
        " après son arrivée.",
        "Les marques du client vont sur les cartons et les étuis pendant la durée, et à"
        " aucun autre usage.",
        "Aucune partie ne peut céder le contrat à un tiers sans l'accord écrit de"
        " l'autre.",
        "Les avis sont donnés par écrit, aux adresses imprimées sur la première page de"
        " ce dossier.",
        "Ce dossier, son calendrier et ces conditions sont l'intégralité de ce que les"
        " parties ont convenu.",
    ),
)

# Every language the pack is written in. A language is added by writing its own set of
# words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH}


def text(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    x: float,
    y: float,
    color: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text with its left edge at ``x`` and its baseline at ``y``."""
    content.set_fill(color)
    content.draw_text(font, size, x, y, s)


def text_right(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    right: float,
    y: float,
    color: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text whose right edge sits at ``right``."""
    text(content, font, size, right - font.measure(s, size), y, color, s)


def rule(
    content: hqf_pdf.Content,
    x1: float,
    x2: float,
    y: float,
    width: float,
    color: hqf_pdf.Rgb,
) -> None:
    """A horizontal rule from ``x1`` to ``x2`` at height ``y``."""
    content.set_stroke(color)
    content.set_line_width(width)
    content.move_to(x1, y)
    content.line_to(x2, y)
    content.stroke()


def full_rule(
    content: hqf_pdf.Content, y: float, width: float, color: hqf_pdf.Rgb
) -> None:
    """A rule across the whole text width, at height ``y``."""
    rule(content, LEFT, RIGHT, y, width, color)


def letterhead_address(words: Words) -> str:
    """The line of small print under the firm's name on the headed sheet."""
    return f"{SUPPLIER_STREET} — {SUPPLIER_TOWN} — {words.vat} {SUPPLIER_VAT}"


def continuation_address() -> str:
    """The one line the continuation sheet carries, which is the firm and where it
    is."""
    return f"{SUPPLIER} — {SUPPLIER_STREET}, {SUPPLIER_TOWN}"


def vat_line(words: Words, number: str) -> str:
    """A tax number as an address block writes it."""
    return f"{words.vat} {number}"


def one_page_sheet(
    font_path, draw: Callable[[hqf_pdf.Content, hqf_pdf.FontHandle], None]
) -> bytes:
    """Puts a one-page document together from what a caller draws on it."""
    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(font_path))

    content = hqf_pdf.Content()
    draw(content, font)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)
    return document.to_bytes()


def a_headed_sheet(font_path, words: Words) -> bytes:
    """The headed sheet: a band across the top with the firm's name and address in
    it."""

    def draw(content: hqf_pdf.Content, font: hqf_pdf.FontHandle) -> None:
        content.save_state()
        content.set_fill(hqf_pdf.Rgb(0.91, 0.94, 0.98))
        content.rect(0.0, 742.0, PAGE_WIDTH, 100.0)
        content.fill()
        content.set_fill(ACCENT)
        content.rect(0.0, 738.0, PAGE_WIDTH, 4.0)
        content.fill()
        content.restore_state()

        text(content, font, 22.0, LEFT, 786.0, INK, SUPPLIER)
        text(content, font, 9.0, LEFT, 764.0, MUTED, letterhead_address(words))

    return one_page_sheet(font_path, draw)


def a_continuation_sheet(font_path) -> bytes:
    """The continuation sheet: the firm's name small at the top, between two
    hairlines."""

    def draw(content: hqf_pdf.Content, font: hqf_pdf.FontHandle) -> None:
        text(content, font, 8.0, LEFT, 806.0, MUTED, continuation_address())
        full_rule(content, 800.0, 0.5, ACCENT)
        full_rule(content, 64.0, 0.5, hqf_pdf.Rgb.gray(0.78))

    return one_page_sheet(font_path, draw)


def clause(words: Words, index: int) -> str:
    """One clause as the conditions sheet numbers it."""
    return f"{index + 1}. {words.clauses[index]}"


def conditions_foot(words: Words) -> str:
    """The line at the foot of the conditions sheet, which says whose conditions they
    are and which edition."""
    return f"{SUPPLIER} — {words.conditions_edition}"


def a_conditions_sheet(font_path, words: Words) -> bytes:
    """The conditions sheet: a heading and the standing clauses, one to a line."""

    def draw(content: hqf_pdf.Content, font: hqf_pdf.FontHandle) -> None:
        text(content, font, 14.0, LEFT, 780.0, INK, words.conditions_title)
        full_rule(content, 770.0, 0.8, ACCENT)

        y = 744.0
        for index in range(len(words.clauses)):
            text(content, font, 8.5, LEFT, y, INK, clause(words, index))
            y -= 26.0

        text(content, font, 8.0, LEFT, 96.0, MUTED, conditions_foot(words))

    return one_page_sheet(font_path, draw)


@dataclass(frozen=True)
class Batch:
    """One line of the schedule: on which day of the quarter it is due, how many, and
    the price of one.

    What is delivered is not here: it is a word, and it lives with the other words of
    its language.
    """

    day: int
    quantity: int
    unit_price: float


# The batches a quarter delivers.
BATCHES = (
    Batch(6, 1200, 7.20),
    Batch(6, 900, 8.40),
    Batch(9, 640, 6.15),
    Batch(13, 480, 11.90),
    Batch(13, 480, 4.35),
    Batch(17, 2400, 0.95),
    Batch(17, 3600, 0.22),
    Batch(20, 120, 3.10),
    Batch(24, 1500, 2.65),
    Batch(24, 3000, 0.48),
    Batch(27, 300, 1.75),
)

# The year each quarter's batches are due in, in the order the schedule runs them. Which
# month it is is a word, and it lives with the words.
YEARS = (2027, 2027, 2027, 2028)


def due(words: Words, batch: Batch, quarter: int) -> str:
    """The day a batch is due, as the schedule writes it."""
    return f"{batch.day} {words.months[quarter]} {YEARS[quarter]}"


def amount(value: float) -> str:
    """An amount, as a schedule writes it: "8 640.00"."""
    units, hundredths = f"{value:.2f}".split(".")
    grouped = ""
    for index, digit in enumerate(units):
        if index > 0 and (len(units) - index) % 3 == 0:
            grouped += " "
        grouped += digit
    return f"{grouped}.{hundredths}"


# The width of each column of the schedule, in points, the first taking whatever the
# other three leave.
DUE_COLUMN = 92.0
QUANTITY_COLUMN = 58.0
VALUE_COLUMN = 78.0

# How much of a cell its text leaves free on each side, and above and below.
CELL_PAD = (6.0, 5.0)


def schedule(font: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Table:
    """The schedule, as one table: a heading drawn again on every page, every batch of
    every quarter, and the total of the lot."""
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(DUE_COLUMN),
            hqf_pdf.ColumnWidth.points(QUANTITY_COLUMN),
            hqf_pdf.ColumnWidth.points(VALUE_COLUMN),
        ],
        TABLE_WIDTH,
    )

    table = hqf_pdf.Table(columns)
    table.header(1)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8, ACCENT))
    table.rule(
        hqf_pdf.Rule.horizontal_other(), hqf_pdf.Stroke(0.25, hqf_pdf.Rgb.gray(0.78))
    )
    table.rule(hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.8, ACCENT))
    table.fill(hqf_pdf.Area.even_rows(), hqf_pdf.Rgb.gray(0.97))
    table.fill(hqf_pdf.Area.header(), ACCENT)

    pad = hqf_pdf.Padding.symmetric(CELL_PAD[0], CELL_PAD[1])

    def heading(label: str, align: hqf_pdf.Align) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            9.0,
            label,
            padding=pad,
            align=align,
            color=hqf_pdf.Rgb.gray(1.0),
            valign=hqf_pdf.VAlign.Middle,
        )

    table.push(
        hqf_pdf.Row(
            [
                heading(words.headings[0], hqf_pdf.Align.Left),
                heading(words.headings[1], hqf_pdf.Align.Left),
                heading(words.headings[2], hqf_pdf.Align.Right),
                heading(words.headings[3], hqf_pdf.Align.Right),
            ],
            min_height=20.0,
        )
    )

    total = 0.0
    for quarter in range(len(YEARS)):
        for index, batch in enumerate(BATCHES):
            value = batch.quantity * batch.unit_price
            total += value
            table.push(
                hqf_pdf.Row(
                    [
                        hqf_pdf.Cell(font, 9.0, words.batches[index], padding=pad),
                        hqf_pdf.Cell(
                            font, 9.0, due(words, batch, quarter), padding=pad
                        ),
                        hqf_pdf.Cell(
                            font,
                            9.0,
                            str(batch.quantity),
                            padding=pad,
                            align=hqf_pdf.Align.Right,
                        ),
                        hqf_pdf.Cell(
                            font,
                            9.0,
                            amount(value),
                            padding=pad,
                            align=hqf_pdf.Align.Right,
                        ),
                    ],
                    min_height=16.0,
                )
            )

    box_margin = hqf_pdf.Margin.symmetric(0.0, 2.0)
    table.push(
        hqf_pdf.Row(
            [
                hqf_pdf.Cell(
                    font,
                    10.0,
                    words.total,
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                    span=3,
                    margin=box_margin,
                ),
                hqf_pdf.Cell(
                    font,
                    10.0,
                    amount(total),
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                    margin=box_margin,
                ),
            ],
            min_height=20.0,
        )
    )

    return table


@dataclass(frozen=True)
class Contents:
    """What the front page can say about the pack once the schedule has said how many
    pages it takes."""

    pages: int
    schedule: tuple[int, int]
    rows: int

    def lines(self, words: Words) -> tuple[tuple[str, str], ...]:
        """The three lines the front page lists the pack by: which pages, and what is
        on them."""
        first, last = self.schedule
        return (
            (f"{words.page} 1", words.front_sheet),
            (
                f"{words.pages} {first} {words.to} {last}",
                f"{words.schedule_before}{self.rows}{words.schedule_after}",
            ),
            (f"{words.page} {self.pages}", words.conditions_entry),
        )


# How far the second column of the list of pages stands from the first.
ENTRY_COLUMN = 96.0

# How long the rule each party signs on is, in points.
SIGNATURE_RULE = 210.0


def party(words: Words, name: str) -> str:
    """What stands over the rule a party signs on."""
    return f"{words.for_party} {name}"


def signatures(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words
) -> None:
    """Draws the two places the parties sign, each a rule with a label under it."""
    text(content, font, 11.0, LEFT, 330.0, ACCENT, words.signed)
    text(content, font, 9.0, LEFT, 312.0, INK, words.signed_note)

    hair = hqf_pdf.Rgb.gray(0.6)
    for x, name in ((LEFT, SUPPLIER), (SECOND_COLUMN, CUSTOMER)):
        rule(content, x, x + SIGNATURE_RULE, 262.0, 0.5, hair)
        text(content, font, 8.0, x, 250.0, MUTED, party(words, name))
        rule(content, x, x + SIGNATURE_RULE, 210.0, 0.5, hair)
        text(content, font, 8.0, x, 198.0, MUTED, words.name_and_date)


def reference_line(words: Words) -> str:
    """The line under the title: what the pack is filed as, and the day it was drawn
    up."""
    return f"{REFERENCE} — {words.drawn_up} {words.drawn_up_on}"


def front_page(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    words: Words,
    contents: Contents,
) -> None:
    """The pack's front page: what it is, who it is between, what it is made of, what
    is in it, and where it is signed."""
    text(content, font, 20.0, LEFT, 700.0, ACCENT, words.title)
    text(content, font, 9.5, LEFT, 682.0, MUTED, reference_line(words))
    full_rule(content, 672.0, 0.8, ACCENT)

    text(content, font, 8.0, LEFT, 652.0, MUTED, words.supplier)
    text(content, font, 8.0, SECOND_COLUMN, 652.0, MUTED, words.customer)

    supplier = (SUPPLIER_STREET, SUPPLIER_TOWN, vat_line(words, SUPPLIER_VAT))
    customer = (CUSTOMER_STREET, CUSTOMER_TOWN, vat_line(words, CUSTOMER_VAT))
    text(content, font, 10.0, LEFT, 637.0, INK, SUPPLIER)
    text(content, font, 10.0, SECOND_COLUMN, 637.0, INK, CUSTOMER)
    y = 624.0
    for theirs, ours in zip(supplier, customer):
        text(content, font, 9.0, LEFT, y, MUTED, theirs)
        text(content, font, 9.0, SECOND_COLUMN, y, MUTED, ours)
        y -= 12.0

    text(content, font, 11.0, LEFT, 566.0, ACCENT, words.made_of)
    y = 548.0
    for line in words.stands_on:
        text(content, font, 9.0, LEFT, y, INK, line)
        y -= 13.0
    y -= 13.0
    for line in words.stamped:
        text(content, font, 9.0, LEFT, y, INK, line)
        y -= 13.0

    text(content, font, 11.0, LEFT, 430.0, ACCENT, words.in_it)
    y = 412.0
    for pages, what in contents.lines(words):
        text(content, font, 9.0, LEFT, y, INK, pages)
        text(content, font, 9.0, LEFT + ENTRY_COLUMN, y, MUTED, what)
        y -= 16.0

    signatures(content, font, words)


def page_number(words: Words, number: int, pages: int) -> str:
    """What every page of the pack carries at its foot."""
    return f"{words.page} {number} {words.of} {pages}"


def add_page(
    document: hqf_pdf.Document,
    sheet: hqf_pdf.ImportedPage,
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    words: Words,
    number: int,
    pages: int,
) -> None:
    """Adds one page to the pack: what the pack drew over its sheet, and the page
    number, which every page carries."""
    text_right(content, font, 8.0, RIGHT, 48.0, MUTED, page_number(words, number, pages))

    leaf = hqf_pdf.Page.a4()
    leaf.set_content(content)
    # A page may only draw what its resources name.
    sheet.add_to(leaf)
    document.add_page(leaf)


def sheet(given: str | None, make: Callable[[], bytes]) -> hqf_pdf.Reader:
    """Reads a sheet named on the command line, or the one made here when none is
    named."""
    if given is not None:
        with open(given, "rb") as handle:
            return hqf_pdf.Reader(handle.read())
    return hqf_pdf.Reader(make())


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(Path(_language.file_name("pack.pdf", language)).stem)
    font_path = _out.DEFAULT_FONT
    given = [sys.argv[index] if len(sys.argv) > index else None for index in (2, 3, 4)]

    headed = sheet(given[0], lambda: a_headed_sheet(font_path, words))
    continuation = sheet(given[1], lambda: a_continuation_sheet(font_path))
    conditions = sheet(given[2], lambda: a_conditions_sheet(font_path, words))

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())

    # Each sheet comes in as a form: the same page, now a drawing this document can
    # stamp wherever it likes, as many times as it likes.
    headed = document.import_page(headed, 0)
    continuation = document.import_page(continuation, 0)
    conditions = document.import_page(conditions, 0)

    font = document.add_font(hqf_pdf.Font.from_path(font_path))
    table = schedule(font, words)

    # The schedule says how many pages it needs, so the pack's length is known before a
    # page of it is made: the front page, the schedule's pages, and the conditions.
    box_of = hqf_pdf.TableFrame(LEFT, TABLE_TOP, TABLE_TOP - TABLE_BOTTOM)
    placed = table.paginate(box_of, box_of)
    pages = len(placed) + 2

    contents = Contents(pages, (2, len(placed) + 1), table.row_count)

    # Each page: its sheet goes down first, and what the pack draws goes on top of it.
    content = hqf_pdf.Content()
    content.draw_form(headed, 0.0, 0.0, 1.0)
    front_page(content, font, words, contents)
    add_page(document, headed, content, font, words, 1, pages)

    for index, placement in enumerate(placed):
        content = hqf_pdf.Content()
        content.draw_form(continuation, 0.0, 0.0, 1.0)
        placement.draw(content)
        add_page(document, continuation, content, font, words, index + 2, pages)

    # The conditions sheet carries nothing of the pack's but its page number: it is a
    # page of the pack, not an attachment to it.
    content = hqf_pdf.Content()
    content.draw_form(conditions, 0.0, 0.0, 1.0)
    add_page(document, conditions, content, font, words, pages, pages)

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, {pages} pages, "
        f"{table.row_count} rows over {len(placed)} of them"
    )


if __name__ == "__main__":
    main()
