"""Writes a mailing of four personal letters into one file made for variable-data
printing: the same layout four times, each copy with its own recipient, seat and amount.

The Python twin of the `write_variable_print` example in Rust. The letterhead and the
note at the foot of each page are one drawing, placed on every page and marked for
reuse (`GTS_XID`, `GTS_Scope File`) and written self-contained, so a press renders it
once and keeps it for the whole file. Each letter is a document part of its own,
stating its recipient, member number, postcode and amount due, so a press knows where
one letter ends and the next begins.

Hand a press profile on the command line and the file claims PDF/VT-1, on PDF/X-4,
written as PDF 1.6. Without one it claims nothing, is written as PDF 2.0, and says on
the page why.

The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which set
the letters are written in. Names, addresses, seats, dates and amounts are not
language.

Usage: python examples/write_variable_print.py [out.pdf] [font.ttf] [press.icc]
       HQF_PDF_LANG=fr python examples/write_variable_print.py
"""

from __future__ import annotations

import sys
from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The A4 sheet, in points.
SHEET = (595.0, 842.0)

# How far in from the left and right edges of the sheet the text stands, in points.
MARGIN = 56.0

# How wide the text runs, in points: the sheet less both margins.
WIDTH = SHEET[0] - 2.0 * MARGIN

# How wide the column of amounts is, in points, at the right of the text.
AMOUNT_WIDTH = 110.0

# How wide the column of what each amount pays for is, in points.
LABEL_WIDTH = WIDTH - AMOUNT_WIDTH

# How far one row of the amounts stands below the one above it, in points.
ROW = 20.0

# Where the letterhead band starts, in points up from the foot of the sheet; it runs to
# the top edge.
HEAD_BOTTOM = 762.0

# Where the band holding the note starts and ends, in points up from the foot of the
# sheet.
NOTE_BAND = (36.0, 206.0)

# How far the note's text stands in from the edges of its band, in points.
NOTE_INSET = 12.0

# How wide the band holding the note is, in points: the text and an inset on either
# side.
NOTE_WIDTH = WIDTH + 2.0 * NOTE_INSET

# The flow the note is set in, by size and leading.
NOTE_TYPE = (8.5, 11.5)

# The colour of the letterhead band.
BAND = hqf_pdf.Cmyk(0.85, 0.55, 0.0, 0.25)

# The colour of the words set on the letterhead band.
ON_BAND = hqf_pdf.Cmyk(0.0, 0.0, 0.0, 0.0)

# The colour of the band behind the note.
NOTE_FILL = hqf_pdf.Cmyk(0.0, 0.0, 0.0, 0.06)

# The colour of the note's words.
NOTE_INK = hqf_pdf.Cmyk(0.0, 0.0, 0.0, 0.75)

# The colour of the letter's words.
INK = hqf_pdf.Cmyk(0.0, 0.0, 0.0, 1.0)

# The colour of the rule above the total.
RULE = hqf_pdf.Cmyk(0.0, 0.0, 0.0, 0.4)

# The concert hall that sends the letters, written the same way in every language.
SENDER = "Aldermoor Hall"

# The day the letters are sent.
SENT = "2026-11-02"

# The day a seat is kept until.
DEADLINE = "2026-12-15"

# When the file was made, which a press reads as the moment it was last written.
MADE = "2026-11-02T08:30:00+01:00"

# The name the output intent states when the profile is the one handed over on the
# command line.
CUSTOM = "Custom"

# What the drawing shared by every page is called among the objects that are the same
# artwork.
SHARED_IDENTITY = "aldermoor-renewal-letterhead"

# The town every recipient lives in.
TOWN = "Aldermoor"


@dataclass(frozen=True)
class Recipient:
    """One recipient of the mailing: what changes from one letter to the next."""

    # The name the letter is addressed to.
    name: str
    # The street line of the address.
    street: str
    # The postcode.
    postcode: str
    # The member number.
    number: str
    # The seat kept for the recipient.
    seat: str
    # Which subscription the recipient holds, as an index into `Words.tiers`.
    tier: int
    # How many seasons the recipient has subscribed for.
    seasons: int
    # What the subscription costs, in cents.
    price: int
    # What the loyalty discount takes off, in cents.
    discount: int

    def due(self) -> int:
        """What the recipient has to pay, in cents."""
        return self.price - self.discount


# The four recipients of the mailing, one letter each.
RECIPIENTS = (
    Recipient(
        name="Ana Ribeiro",
        street="14 Quay Street",
        postcode="AL1 4QD",
        number="A-10482",
        seat="F-12",
        tier=0,
        seasons=6,
        price=42_000,
        discount=4_200,
    ),
    Recipient(
        name="Tomasz Nowak",
        street="3 Mill Lane",
        postcode="AL2 7RB",
        number="A-11937",
        seat="K-03",
        tier=1,
        seasons=2,
        price=23_000,
        discount=1_150,
    ),
    Recipient(
        name="Mei Chen",
        street="27 Orchard Rise",
        postcode="AL3 9JT",
        number="A-12260",
        seat="R-21",
        tier=2,
        seasons=2,
        price=9_000,
        discount=450,
    ),
    Recipient(
        name="Pieter de Vries",
        street="8 Bell Yard",
        postcode="AL1 2HX",
        number="A-08815",
        seat="B-07",
        tier=3,
        seasons=12,
        price=90_000,
        discount=9_000,
    ),
)


@dataclass(frozen=True)
class Words:
    """Every word the letters set, in one language."""

    # What the file as a whole is called.
    title: str
    # What the hall is, set under its name on the letterhead.
    tagline: str
    # The words a member number is introduced by.
    member: str
    # The words the day the letter is sent is introduced by.
    sent: str
    # The heading of every letter.
    heading: str
    # How a letter opens; `{name}` stands for the recipient's name.
    greeting: str
    # What every letter says; `{seat}` stands for the seat and `{date}` for the day the
    # seat is kept until.
    body: str
    # What each of the four subscriptions is called, in the order of `Recipient.tier`.
    tiers: tuple[str, str, str, str]
    # What the discount row is; `{seasons}` stands for how many seasons.
    discount: str
    # What the total row is.
    total: str
    # How a letter closes; `{date}` stands for the day the seat is kept until.
    closing: str
    # Who signs the letters.
    signature: str
    # The heading of the note at the foot of every page.
    note_title: str
    # The note at the foot of every page, saying what the file tells a press.
    note: str
    # The last line of the note when the file claims PDF/VT.
    claimed: str
    # The last line of the note when the file claims nothing.
    unclaimed: str
    # What the output intent says of the profile handed over on the command line.
    press: str


ENGLISH = Words(
    title="Season renewal letters, 2027",
    tagline="Concert hall · 2027 season",
    member="Member no.",
    sent="sent on",
    heading="Your seat for the 2027 season",
    greeting="Dear {name},",
    body=(
        "Your subscription ends with the last concert of this season. To keep seat "
        "{seat} for 2027, renew before {date}. The amount below already takes off your "
        "loyalty discount."
    ),
    tiers=(
        "Full season subscription",
        "Half season subscription",
        "Student subscription",
        "Patron subscription",
    ),
    discount="Loyalty discount, {seasons} seasons with us",
    total="To pay",
    closing=(
        "Reply to this letter or call the box office before {date}. We look forward to "
        "seeing you in the hall."
    ),
    signature="The box office",
    note_title="Four letters, one layout, one file",
    note=(
        "These four letters share one layout and differ only in who they are for, the "
        "seat and the amount. The file tells the press so. Each letter is a part of "
        "its own, stating the recipient, the member number, the postcode and the "
        "amount due. The letterhead and this note are a single drawing, placed on "
        "every page and marked to be rendered once and kept for the whole file. This "
        "is variable-data printing: a run of thousands of personal letters sent to the "
        "press as one file and printed at full speed."
    ),
    claimed=(
        "This file claims PDF/VT-1, on PDF/X-4, for the press profile it was given."
    ),
    unclaimed=(
        "This copy claims no standard: PDF/VT rests on PDF/X-4, which needs the "
        "profile of the press the run is printed on. Give one on the command line and "
        "the same file claims both."
    ),
    press="A press profile handed over on the command line",
)


FRENCH = Words(
    title="Lettres de réabonnement, saison 2027",
    tagline="Salle de concert · saison 2027",
    member="N° d’abonné",
    sent="envoyée le",
    heading="Votre place pour la saison 2027",
    greeting="Bonjour {name},",
    body=(
        "Votre abonnement prend fin avec le dernier concert de cette saison. Pour "
        "conserver la place {seat} en 2027, renouvelez-le avant le {date}. Le montant "
        "ci-dessous tient déjà compte de votre remise de fidélité."
    ),
    tiers=(
        "Abonnement saison complète",
        "Abonnement demi-saison",
        "Abonnement étudiant",
        "Abonnement mécène",
    ),
    discount="Remise de fidélité, {seasons} saisons à nos côtés",
    total="Montant à régler",
    closing=(
        "Répondez simplement à ce courrier ou appelez la billetterie avant le {date}. "
        "Nous nous réjouissons de vous retrouver dans la salle."
    ),
    signature="La billetterie",
    note_title="Quatre lettres, une mise en page, un seul fichier",
    note=(
        "Ces quatre lettres partagent la même mise en page ; seuls changent le "
        "destinataire, la place et le montant. Le fichier l’indique à la presse. "
        "Chaque lettre constitue une partie distincte du document, qui précise le "
        "destinataire, le numéro d’abonné, le code postal et le montant dû. L’en-tête "
        "et cette note sont un seul et même objet graphique, placé sur chaque page et "
        "marqué pour être traité une seule fois par le RIP, puis conservé pour tout le "
        "fichier. C’est de l’impression de données variables : un tirage de milliers "
        "de lettres personnalisées, envoyé à la presse en un seul fichier et imprimé à "
        "pleine vitesse."
    ),
    claimed=(
        "Ce fichier déclare la conformité à PDF/VT-1, sur une base PDF/X-4, pour le "
        "profil de presse qui lui a été fourni."
    ),
    unclaimed=(
        "Cet exemplaire ne déclare la conformité à aucune norme : PDF/VT repose sur "
        "PDF/X-4, qui exige le profil de la presse utilisée pour le tirage. "
        "Fournissez-en un en ligne de commande et le même fichier déclarera la "
        "conformité aux deux."
    ),
    press="Profil de presse fourni en ligne de commande",
)


GERMAN = Words(
    title="Verlängerungsschreiben zur Saison 2027",
    tagline="Konzerthaus · Saison 2027",
    member="Abonnenten-Nr.",
    sent="versandt am",
    heading="Ihr Platz in der Saison 2027",
    greeting="Guten Tag {name},",
    body=(
        "Ihr Abonnement endet mit dem letzten Konzert dieser Saison. Damit Ihnen Platz "
        "{seat} auch 2027 erhalten bleibt, verlängern Sie bitte bis zum {date}. Ihr "
        "Treuerabatt ist im unten stehenden Betrag bereits abgezogen."
    ),
    tiers=(
        "Abonnement für die ganze Saison",
        "Abonnement für die halbe Saison",
        "Abonnement für Studierende",
        "Förderabonnement",
    ),
    discount="Treuerabatt für {seasons} Saisons bei uns",
    total="Zu zahlen",
    closing=(
        "Antworten Sie auf dieses Schreiben oder rufen Sie bis zum {date} die "
        "Konzertkasse an. Wir freuen uns, Sie im Saal begrüßen zu dürfen."
    ),
    signature="Ihre Konzertkasse",
    note_title="Vier Briefe, ein Layout, eine Datei",
    note=(
        "Diese vier Briefe haben dasselbe Layout und unterscheiden sich nur in "
        "Empfänger, Sitzplatz und Betrag. Die Datei teilt das der Druckmaschine mit. "
        "Jeder Brief ist ein eigener Dokumentteil und nennt Empfänger, "
        "Abonnentennummer, Postleitzahl und fälligen Betrag. Briefkopf und dieser "
        "Hinweis sind ein einziges Grafikobjekt, das auf jeder Seite platziert und so "
        "gekennzeichnet ist, dass es ein einziges Mal gerastert und für die ganze "
        "Datei vorgehalten wird. Das ist variabler Datendruck: Eine Auflage von "
        "Tausenden persönlicher Briefe geht als eine einzige Datei an die "
        "Druckmaschine und wird mit voller Geschwindigkeit gedruckt."
    ),
    claimed=(
        "Diese Datei erklärt Konformität mit PDF/VT-1 auf Basis von PDF/X-4, bezogen "
        "auf das übergebene Farbprofil der Druckmaschine."
    ),
    unclaimed=(
        "Dieses Exemplar erklärt keine Normkonformität: PDF/VT baut auf PDF/X-4 auf, "
        "und PDF/X-4 verlangt das Farbprofil der Druckmaschine, auf der die Auflage "
        "gedruckt wird. Wird es auf der Kommandozeile übergeben, erklärt dieselbe "
        "Datei Konformität mit beiden Normen."
    ),
    press="Farbprofil der Druckmaschine, über die Kommandozeile übergeben",
)


SPANISH = Words(
    title="Cartas de renovación del abono, 2027",
    tagline="Sala de conciertos · temporada 2027",
    member="N.º de abonado",
    sent="enviada el",
    heading="Su butaca para la temporada 2027",
    greeting="Buenos días, {name}:",
    body=(
        "Su abono termina con el último concierto de esta temporada. Para conservar la "
        "butaca {seat} en 2027, renuévelo antes del {date}. El importe que figura "
        "abajo ya lleva aplicado su descuento por fidelidad."
    ),
    tiers=(
        "Abono de temporada completa",
        "Abono de media temporada",
        "Abono de estudiante",
        "Abono de mecenas",
    ),
    discount="Descuento por fidelidad: {seasons} temporadas con nosotros",
    total="Total a pagar",
    closing=(
        "Responda a esta carta o llame a la taquilla antes del {date}. Será un placer "
        "volver a verle en la sala."
    ),
    signature="La taquilla",
    note_title="Cuatro cartas, una maqueta, un solo archivo",
    note=(
        "Estas cuatro cartas comparten la misma maqueta y solo se diferencian en el "
        "destinatario, la butaca y el importe. El archivo se lo comunica así a la "
        "máquina de impresión. Cada carta es una parte propia del documento, que "
        "indica el destinatario, el número de abonado, el código postal y el importe "
        "pendiente. El membrete y esta nota son un único objeto gráfico, colocado en "
        "todas las páginas y marcado para que el RIP lo rasterice una sola vez y lo "
        "conserve durante todo el archivo. Esto es impresión de datos variables: una "
        "tirada de miles de cartas personalizadas que llega a la máquina de impresión "
        "en un único archivo y se imprime a máxima velocidad."
    ),
    claimed=(
        "Este archivo declara la conformidad con PDF/VT-1, sobre PDF/X-4, para el "
        "perfil de la máquina de impresión que se le indicó."
    ),
    unclaimed=(
        "Este ejemplar no declara la conformidad con ninguna norma: PDF/VT se apoya en "
        "PDF/X-4, que exige el perfil de la máquina en la que se imprime la tirada. "
        "Indíquelo en la línea de comandos y el mismo archivo declarará ambas."
    ),
    press="Perfil de la máquina de impresión indicado en la línea de comandos",
)


ITALIAN = Words(
    title="Lettere di rinnovo degli abbonamenti, stagione 2027",
    tagline="Sala da concerto · stagione 2027",
    member="N. abbonato",
    sent="inviata il",
    heading="Il Suo posto per la stagione 2027",
    greeting="Gentile {name},",
    body=(
        "Il Suo abbonamento scade con l’ultimo concerto di questa stagione. Per "
        "conservare il posto {seat} anche nel 2027, La preghiamo di rinnovarlo entro "
        "il {date}. L’importo indicato qui sotto è già al netto del Suo sconto "
        "fedeltà."
    ),
    tiers=(
        "Abbonamento intera stagione",
        "Abbonamento mezza stagione",
        "Abbonamento studenti",
        "Abbonamento sostenitore",
    ),
    discount="Sconto fedeltà: {seasons} stagioni con noi",
    total="Totale da pagare",
    closing=(
        "Risponda a questa lettera o chiami la biglietteria entro il {date}. Saremo "
        "lieti di rivederLa in sala."
    ),
    signature="La biglietteria",
    note_title="Quattro lettere, una sola impaginazione, un solo file",
    note=(
        "Queste quattro lettere hanno la stessa impaginazione e cambiano soltanto per "
        "destinatario, posto e importo: è proprio questo che il file comunica alla "
        "macchina da stampa. Ogni lettera è una parte a sé del documento e ne indica "
        "il destinatario, il numero di abbonato, il CAP e l’importo dovuto. "
        "L’intestazione e questa nota sono un unico oggetto grafico, collocato su ogni "
        "pagina e contrassegnato perché il RIP lo elabori una sola volta e lo conservi "
        "per l’intero file. È la stampa a dati variabili: una tiratura di migliaia di "
        "lettere personalizzate inviata alla macchina in un solo file e stampata alla "
        "massima velocità."
    ),
    claimed=(
        "Questo file dichiara la conformità a PDF/VT-1, basato su PDF/X-4, per il "
        "profilo della macchina da stampa che gli è stato fornito."
    ),
    unclaimed=(
        "Questa copia non dichiara alcuna norma: PDF/VT si fonda su PDF/X-4, che "
        "richiede il profilo della macchina su cui si stampa la tiratura. Lo si "
        "indichi sulla riga di comando e lo stesso file dichiarerà la conformità a "
        "entrambe."
    ),
    press="Profilo della macchina da stampa fornito sulla riga di comando",
)


PORTUGUESE = Words(
    title="Cartas de renovação da assinatura, temporada 2027",
    tagline="Sala de concertos · temporada 2027",
    member="N.º de assinante",
    sent="enviada a",
    heading="O seu lugar na temporada 2027",
    greeting="Caro(a) {name},",
    body=(
        "A sua assinatura termina com o último concerto desta temporada. Para manter o "
        "lugar {seat} em 2027, renove-a antes de {date}. O montante abaixo já inclui o "
        "seu desconto de fidelidade."
    ),
    tiers=(
        "Assinatura de temporada completa",
        "Assinatura de meia temporada",
        "Assinatura de estudante",
        "Assinatura de mecenas",
    ),
    discount="Desconto de fidelidade, {seasons} temporadas connosco",
    total="A pagar",
    closing=(
        "Responda a esta carta ou telefone para a bilheteira antes de {date}. Contamos "
        "com a sua presença na sala."
    ),
    signature="A bilheteira",
    note_title="Quatro cartas, uma paginação, um ficheiro",
    note=(
        "Estas quatro cartas partilham a mesma paginação e só diferem no destinatário, "
        "no lugar e no montante. E o ficheiro di-lo à máquina de impressão. Cada carta "
        "é uma parte própria do documento, com o destinatário, o número de assinante, "
        "o código postal e o montante devido. O cabeçalho e esta nota são um único "
        "objeto gráfico, colocado em todas as páginas e marcado para ser rasterizado "
        "uma só vez e conservado para todo o ficheiro. Isto é impressão de dados "
        "variáveis: uma tiragem de milhares de cartas personalizadas enviada à máquina "
        "como um só ficheiro e impressa à velocidade máxima."
    ),
    claimed=(
        "Este ficheiro declara conformidade com PDF/VT-1, assente em PDF/X-4, para o "
        "perfil da máquina de impressão que lhe foi fornecido."
    ),
    unclaimed=(
        "Esta cópia não declara conformidade com nenhuma norma: o PDF/VT assenta no "
        "PDF/X-4, que exige o perfil da máquina de impressão onde a tiragem é feita. "
        "Indique-o na linha de comandos e o mesmo ficheiro passa a declarar as duas."
    ),
    press="Perfil da máquina de impressão indicado na linha de comandos",
)


DUTCH = Words(
    title="Verlengingsbrieven seizoen 2027",
    tagline="Concertzaal · seizoen 2027",
    member="Abonneenr.",
    sent="verstuurd op",
    heading="Uw plaats in seizoen 2027",
    greeting="Beste {name},",
    body=(
        "Uw abonnement loopt af na het laatste concert van dit seizoen. Wilt u plaats "
        "{seat} ook in 2027 houden, verleng dan vóór {date}. Op het bedrag hieronder "
        "is uw loyaliteitskorting al in mindering gebracht."
    ),
    tiers=(
        "Abonnement hele seizoen",
        "Abonnement half seizoen",
        "Studentenabonnement",
        "Begunstigersabonnement",
    ),
    discount="Loyaliteitskorting, al {seasons} seizoenen bij ons",
    total="Te betalen",
    closing=(
        "Beantwoord deze brief of bel vóór {date} met de klantenservice. We zien u "
        "graag terug in de zaal."
    ),
    signature="De klantenservice",
    note_title="Vier brieven, één opmaak, één bestand",
    note=(
        "Deze vier brieven hebben dezelfde opmaak en verschillen alleen in ontvanger, "
        "plaats en bedrag. Dat staat ook in het bestand voor de drukpers. Elke brief "
        "is een eigen documentdeel met de ontvanger, het abonneenummer, de postcode en "
        "het verschuldigde bedrag. Het briefhoofd en deze notitie vormen één gedeeld "
        "grafisch object dat op elke pagina staat en zo is gemarkeerd dat de RIP het "
        "één keer rastert en voor het hele bestand bewaart. Dit is drukken met "
        "variabele data: een oplage van duizenden persoonlijke brieven die als één "
        "bestand naar de drukpers gaat en op volle snelheid wordt gedrukt."
    ),
    claimed=(
        "Dit bestand verklaart te voldoen aan PDF/VT-1, op basis van PDF/X-4, voor het "
        "opgegeven ICC-profiel van de drukpers."
    ),
    unclaimed=(
        "Dit exemplaar verklaart aan geen enkele norm te voldoen: PDF/VT bouwt voort "
        "op PDF/X-4, en daarvoor is het ICC-profiel nodig van de drukpers waarop de "
        "oplage wordt gedrukt. Geef dat profiel op via de opdrachtregel, dan verklaart "
        "hetzelfde bestand aan beide te voldoen."
    ),
    press="ICC-profiel van de drukpers, opgegeven via de opdrachtregel",
)


# Every language the example 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,
    _language.GERMAN: GERMAN,
    _language.SPANISH: SPANISH,
    _language.ITALIAN: ITALIAN,
    _language.PORTUGUESE: PORTUGUESE,
    _language.DUTCH: DUTCH,
}


def money(cents: int) -> str:
    """An amount, with a space between its thousands, a point before its cents and a
    hyphen before it when it is taken off."""
    sign = "-" if cents < 0 else ""
    whole, fraction = abs(cents) // 100, abs(cents) % 100
    digits = str(whole)
    grouped = ""
    for index, digit in enumerate(digits):
        if index > 0 and (len(digits) - index) % 3 == 0:
            grouped += " "
        grouped += digit
    return f"{sign}{grouped}.{fraction:02d} EUR"


def ink_flow(
    handle: hqf_pdf.FontHandle,
    size: float,
    leading: float,
    align: hqf_pdf.Align = hqf_pdf.Align.Left,
) -> hqf_pdf.TextFlow:
    """The flow the letter sets its words in, at `size` points on `leading`."""
    return hqf_pdf.TextFlow(handle, size, align=align, leading=leading, color=INK)


def row_flow(handle: hqf_pdf.FontHandle, align: hqf_pdf.Align) -> hqf_pdf.TextFlow:
    """The flow one row of the amounts sets its label in, and its amount."""
    return ink_flow(handle, 10.5, 14.0, align)


def set_text(
    content: hqf_pdf.Content,
    flow: hqf_pdf.TextFlow,
    text: str,
    x: float,
    top: float,
    width: float,
) -> float:
    """Sets `text` in `flow` across `width` points from `x`, its top at `top`, and
    returns how tall it stands."""
    lines = flow.break_lines(text, width)
    flow.draw(content, lines, x, top, width)
    return flow.height(lines)


def note_lines(words: Words, claims: bool) -> tuple[str, str]:
    """The words of the note at the foot of every page, its last line saying whether
    the file claims PDF/VT."""
    return (words.note, words.claimed if claims else words.unclaimed)


def shared(
    content: hqf_pdf.Content, handle: hqf_pdf.FontHandle, words: Words, claims: bool
) -> float:
    """Sets the letterhead and the note on `content`, and returns where the note's last
    line ends, in points up from the foot of the sheet."""
    content.save_state()
    content.set_fill(BAND)
    content.rect(0.0, HEAD_BOTTOM, SHEET[0], SHEET[1] - HEAD_BOTTOM)
    content.fill()
    content.set_fill(NOTE_FILL)
    content.rect(
        MARGIN - NOTE_INSET,
        NOTE_BAND[0],
        NOTE_WIDTH,
        NOTE_BAND[1] - NOTE_BAND[0],
    )
    content.fill()

    name = hqf_pdf.TextFlow(handle, 20.0, leading=24.0, color=ON_BAND)
    set_text(content, name, SENDER, MARGIN, 822.0, WIDTH)
    tagline = hqf_pdf.TextFlow(handle, 9.5, leading=12.0, color=ON_BAND)
    set_text(content, tagline, words.tagline, MARGIN, 792.0, WIDTH)

    top = NOTE_BAND[1] - NOTE_INSET
    heading = hqf_pdf.TextFlow(handle, 10.5, leading=14.0, color=NOTE_INK)
    top -= set_text(content, heading, words.note_title, MARGIN, top, WIDTH) + 3.0
    note = hqf_pdf.TextFlow(
        handle, NOTE_TYPE[0], leading=NOTE_TYPE[1], color=NOTE_INK
    )
    for line in note_lines(words, claims):
        top -= set_text(content, note, line, MARGIN, top, WIDTH) + 4.0
    content.restore_state()
    return top + 4.0


def shared_drawing(
    handle: hqf_pdf.FontHandle, words: Words, claims: bool
) -> hqf_pdf.Drawing:
    """The drawing every page shares: the letterhead and the note, marked for a press
    to render once and keep for the whole file, and written self-contained."""
    content = hqf_pdf.Content()
    shared(content, handle, words, claims)
    hints = (
        hqf_pdf.ReuseHints()
        .with_identity(SHARED_IDENTITY)
        .with_scope(hqf_pdf.ReuseScope.File)
    )
    return (
        hqf_pdf.Drawing(content, hqf_pdf.Rect(0.0, 0.0, SHEET[0], SHEET[1]))
        .with_reuse(hints)
        .encapsulated()
    )


def letter(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    words: Words,
    recipient: Recipient,
) -> float:
    """Sets the letter to `recipient` in `words` onto `content`, from under the
    letterhead down, and returns where its last line ends, in points up from the foot
    of the sheet."""
    content.save_state()
    top = 728.0

    address = ink_flow(handle, 11.0, 14.0)
    for line in (
        recipient.name,
        recipient.street,
        f"{recipient.postcode} {TOWN}",
    ):
        top -= set_text(content, address, line, MARGIN, top, WIDTH)
    top -= 22.0

    small = ink_flow(handle, 9.0, 12.0)
    reference = f"{words.member} {recipient.number} · {words.sent} {SENT}"
    top -= set_text(content, small, reference, MARGIN, top, WIDTH) + 28.0

    heading = ink_flow(handle, 17.0, 21.0)
    top -= set_text(content, heading, words.heading, MARGIN, top, WIDTH) + 14.0

    body = ink_flow(handle, 10.5, 15.0)
    greeting = words.greeting.replace("{name}", recipient.name)
    top -= set_text(content, body, greeting, MARGIN, top, WIDTH) + 6.0
    said = words.body.replace("{seat}", recipient.seat).replace("{date}", DEADLINE)
    top -= set_text(content, body, said, MARGIN, top, WIDTH) + 16.0

    label = row_flow(handle, hqf_pdf.Align.Left)
    amount = row_flow(handle, hqf_pdf.Align.Right)
    discount = words.discount.replace("{seasons}", str(recipient.seasons))
    for what, cents in (
        (words.tiers[recipient.tier], recipient.price),
        (discount, -recipient.discount),
    ):
        set_text(content, label, what, MARGIN, top, LABEL_WIDTH)
        set_text(content, amount, money(cents), MARGIN + LABEL_WIDTH, top, AMOUNT_WIDTH)
        top -= ROW
    content.set_stroke(RULE)
    content.set_line_width(0.5)
    content.move_to(MARGIN, top - 2.0)
    content.line_to(MARGIN + WIDTH, top - 2.0)
    content.stroke()
    top -= 8.0
    set_text(content, label, words.total, MARGIN, top, LABEL_WIDTH)
    set_text(
        content,
        amount,
        money(recipient.due()),
        MARGIN + LABEL_WIDTH,
        top,
        AMOUNT_WIDTH,
    )
    top -= ROW + 12.0

    closing = words.closing.replace("{date}", DEADLINE)
    top -= set_text(content, body, closing, MARGIN, top, WIDTH) + 14.0
    top -= set_text(content, body, words.signature, MARGIN, top, WIDTH)
    top -= set_text(content, body, SENDER, MARGIN, top, WIDTH)
    content.restore_state()
    return top


def stated(recipient: Recipient) -> hqf_pdf.PartData:
    """What one letter states about itself, for the press that prints it."""
    return hqf_pdf.PartData(
        entries=[
            ("Recipient", recipient.name),
            ("MemberNumber", recipient.number),
            ("Postcode", recipient.postcode),
            ("AmountDue", recipient.due() / 100.0),
        ]
    )


def hierarchy() -> hqf_pdf.DocumentParts:
    """The hierarchy: one part per letter, each taking the next page, under the part
    that is the whole mailing."""
    letters = [
        hqf_pdf.DocumentPart(next_pages=1, data=stated(recipient))
        for recipient in RECIPIENTS
    ]
    return hqf_pdf.DocumentParts(
        hqf_pdf.DocumentPart(children=letters),
        node_names=["Mailing", "Recipient"],
        record_level=1,
    )


def build(words: Words, font: Path, press: bytes | None) -> bytes:
    """The four letters as one file, claiming PDF/VT-1 on PDF/X-4 when `press` is the
    profile of a press, and nothing otherwise."""
    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_metadata(
        hqf_pdf.Metadata(
            title=words.title,
            producer="hqf-pdf",
            created=MADE,
            trapped=hqf_pdf.Trapped.No,
            # The print standard asks for the program the job was made with.
            creator="hqf-pdf" if press is not None else None,
        )
    )

    if press is not None:
        described = hqf_pdf.icc_profile_space(press)
        if described is None:
            raise SystemExit("the press profile must describe CMYK")
        document.set_output_intent(
            hqf_pdf.OutputIntent(
                hqf_pdf.IccBased(press, described), CUSTOM, words.press
            )
        )
        document.set_print_conformance(hqf_pdf.PdfX.X4)
        document.set_variable_print_conformance(hqf_pdf.PdfVt.Vt1)
        document.set_version(hqf_pdf.Version.V1_6)
    else:
        document.set_version(hqf_pdf.Version.V2_0)

    handle = document.add_font(hqf_pdf.Font.from_path(font))
    background = document.add_drawing(
        shared_drawing(handle, words, press is not None)
    )

    for recipient in RECIPIENTS:
        content = hqf_pdf.Content()
        content.draw_form(background, 0.0, 0.0, 1.0)
        letter(content, handle, words, recipient)
        page = hqf_pdf.Page(SHEET[0], SHEET[1])
        page.set_content(content)
        page.set_trim_box(hqf_pdf.Rect(0.0, 0.0, SHEET[0], SHEET[1]))
        document.add_page(page)
    document.set_document_parts(hierarchy())
    return document.to_bytes()


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
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(
        Path(_language.file_name("variable_print.pdf", language)).stem
    )
    press = Path(sys.argv[3]).read_bytes() if len(sys.argv) > 3 else None

    data = build(words, _out.font_path(), press)
    Path(out).parent.mkdir(parents=True, exist_ok=True)
    Path(out).write_bytes(data)
    claim = "claiming PDF/VT-1 on PDF/X-4" if press is not None else "claiming nothing"
    print(f"wrote {out}: {len(data)} bytes, {len(RECIPIENTS)} letters, {claim}")


if __name__ == "__main__":
    main()
