"""Writes a tagged notice whose structure tree says more than what each run is, and
whose furniture says what kind of furniture it is.

The Python twin of the `write_tagged_structure` example in Rust. The first page is the
notice. Its tree says where each element stands in the flow — a heading set as a block,
a word inline, a caption before the table, a label at the start of the lines, an aside
floated to their end — what an element is for in the web's vocabulary, what an
abbreviation stands for, and which header cells each cell of its table sits under, the
headers spanning rows and columns and each stating what it heads. Its furniture is
marked as furniture of every kind a page carries: a background, a watermark, a running
head, line numbers, a page number, a Bates number, a redaction and the marks a trimmer
cuts to. The running head carries its own facts on runs no element of the tree owns: an
abbreviation written out, a ligature read as its two letters, a tick drawn as a path
described in words, a phrase in another language.

The second page sets a list for each numbering a list can state, labelled the way that
numbering reads. The third names every role an element can be given, as the tree writes
it.

The file is written as PDF 2.0, which the placements, the roles and most of the kinds of
furniture belong to. It claims no standard.

One bookmark leads to the header cell over the two seasons, tied to the element by its
identifier rather than to a place on the page.

Every sentence is held in `Words`, once per language, and `HQF_PDF_LANG` picks which set
is drawn. The names of the numberings and of the roles are not words: they are what the
file writes.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The left edge the text of the notice lines up on.
LEFT = 100.0

# How wide the text of the notice runs.
WIDTH = 330.0

# The size and the leading of the notice's running text.
BODY = (10.5, 15.0)

# The Bates number the first page carries; each page after it carries the next.
FIRST_BATES = 101

# What the table counts: paper in spring and in autumn, then ink.
COUNTS = (("120", "80"), ("15", "22"))

# Every numbering a list can state, and the two labels each one reads as.
NUMBERINGS = (
    (hqf_pdf.ListNumbering.NoNumbering, ("", "")),
    (hqf_pdf.ListNumbering.Unordered, ("–", "–")),
    (hqf_pdf.ListNumbering.Description, ("", "")),
    (hqf_pdf.ListNumbering.Disc, ("•", "•")),
    (hqf_pdf.ListNumbering.Circle, ("◦", "◦")),
    (hqf_pdf.ListNumbering.Square, ("▪", "▪")),
    (hqf_pdf.ListNumbering.Ordered, ("1)", "2)")),
    (hqf_pdf.ListNumbering.Decimal, ("1.", "2.")),
    (hqf_pdf.ListNumbering.UpperRoman, ("I.", "II.")),
    (hqf_pdf.ListNumbering.LowerRoman, ("i.", "ii.")),
    (hqf_pdf.ListNumbering.UpperAlpha, ("A.", "B.")),
    (hqf_pdf.ListNumbering.LowerAlpha, ("a.", "b.")),
)

# Every role an element of the tree can be given.
ROLES = (
    hqf_pdf.AriaRole.Alert,
    hqf_pdf.AriaRole.AlertDialog,
    hqf_pdf.AriaRole.Application,
    hqf_pdf.AriaRole.Article,
    hqf_pdf.AriaRole.Banner,
    hqf_pdf.AriaRole.Button,
    hqf_pdf.AriaRole.Cell,
    hqf_pdf.AriaRole.Checkbox,
    hqf_pdf.AriaRole.ColumnHeader,
    hqf_pdf.AriaRole.ComboBox,
    hqf_pdf.AriaRole.Complementary,
    hqf_pdf.AriaRole.ContentInfo,
    hqf_pdf.AriaRole.Definition,
    hqf_pdf.AriaRole.Dialog,
    hqf_pdf.AriaRole.Directory,
    hqf_pdf.AriaRole.Document,
    hqf_pdf.AriaRole.Feed,
    hqf_pdf.AriaRole.Figure,
    hqf_pdf.AriaRole.Form,
    hqf_pdf.AriaRole.Grid,
    hqf_pdf.AriaRole.GridCell,
    hqf_pdf.AriaRole.Group,
    hqf_pdf.AriaRole.Heading,
    hqf_pdf.AriaRole.Img,
    hqf_pdf.AriaRole.Link,
    hqf_pdf.AriaRole.List,
    hqf_pdf.AriaRole.ListBox,
    hqf_pdf.AriaRole.ListItem,
    hqf_pdf.AriaRole.Log,
    hqf_pdf.AriaRole.Main,
    hqf_pdf.AriaRole.Marquee,
    hqf_pdf.AriaRole.Math,
    hqf_pdf.AriaRole.Menu,
    hqf_pdf.AriaRole.MenuBar,
    hqf_pdf.AriaRole.MenuItem,
    hqf_pdf.AriaRole.MenuItemCheckbox,
    hqf_pdf.AriaRole.MenuItemRadio,
    hqf_pdf.AriaRole.Navigation,
    hqf_pdf.AriaRole.Note,
    hqf_pdf.AriaRole.Option,
    hqf_pdf.AriaRole.Presentation,
    hqf_pdf.AriaRole.ProgressBar,
    hqf_pdf.AriaRole.Radio,
    hqf_pdf.AriaRole.RadioGroup,
    hqf_pdf.AriaRole.Region,
    hqf_pdf.AriaRole.Row,
    hqf_pdf.AriaRole.RowGroup,
    hqf_pdf.AriaRole.RowHeader,
    hqf_pdf.AriaRole.ScrollBar,
    hqf_pdf.AriaRole.Search,
    hqf_pdf.AriaRole.SearchBox,
    hqf_pdf.AriaRole.Separator,
    hqf_pdf.AriaRole.Slider,
    hqf_pdf.AriaRole.SpinButton,
    hqf_pdf.AriaRole.Status,
    hqf_pdf.AriaRole.Switch,
    hqf_pdf.AriaRole.Tab,
    hqf_pdf.AriaRole.Table,
    hqf_pdf.AriaRole.TabList,
    hqf_pdf.AriaRole.TabPanel,
    hqf_pdf.AriaRole.Term,
    hqf_pdf.AriaRole.TextBox,
    hqf_pdf.AriaRole.Timer,
    hqf_pdf.AriaRole.ToolBar,
    hqf_pdf.AriaRole.ToolTip,
    hqf_pdf.AriaRole.Tree,
    hqf_pdf.AriaRole.TreeGrid,
    hqf_pdf.AriaRole.TreeItem,
    hqf_pdf.AriaRole.DocAbstract,
    hqf_pdf.AriaRole.DocAcknowledgments,
    hqf_pdf.AriaRole.DocAfterword,
    hqf_pdf.AriaRole.DocAppendix,
    hqf_pdf.AriaRole.DocBackLink,
    hqf_pdf.AriaRole.DocBiblioEntry,
    hqf_pdf.AriaRole.DocBibliography,
    hqf_pdf.AriaRole.DocBiblioRef,
    hqf_pdf.AriaRole.DocChapter,
    hqf_pdf.AriaRole.DocColophon,
    hqf_pdf.AriaRole.DocConclusion,
    hqf_pdf.AriaRole.DocCover,
    hqf_pdf.AriaRole.DocCredit,
    hqf_pdf.AriaRole.DocCredits,
    hqf_pdf.AriaRole.DocDedication,
    hqf_pdf.AriaRole.DocEndnote,
    hqf_pdf.AriaRole.DocEndnotes,
    hqf_pdf.AriaRole.DocEpigraph,
    hqf_pdf.AriaRole.DocEpilogue,
    hqf_pdf.AriaRole.DocErrata,
    hqf_pdf.AriaRole.DocExample,
    hqf_pdf.AriaRole.DocFootnote,
    hqf_pdf.AriaRole.DocForeword,
    hqf_pdf.AriaRole.DocGlossary,
    hqf_pdf.AriaRole.DocGlossRef,
    hqf_pdf.AriaRole.DocIndex,
    hqf_pdf.AriaRole.DocIntroduction,
    hqf_pdf.AriaRole.DocNoteRef,
    hqf_pdf.AriaRole.DocNotice,
    hqf_pdf.AriaRole.DocPageBreak,
    hqf_pdf.AriaRole.DocPageList,
    hqf_pdf.AriaRole.DocPart,
    hqf_pdf.AriaRole.DocPreface,
    hqf_pdf.AriaRole.DocPrologue,
    hqf_pdf.AriaRole.DocPullQuote,
    hqf_pdf.AriaRole.DocQna,
    hqf_pdf.AriaRole.DocSubtitle,
    hqf_pdf.AriaRole.DocTip,
    hqf_pdf.AriaRole.DocToc,
)


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

    What is not language stays out of it: the counts in the table, the Bates numbers,
    the list labels, and the names of the numberings and of the roles.
    """

    # The language the tree declares the document is written in.
    lang: str
    # The notice's heading.
    title: str
    # The bookmark that leads to the heading over the seasons.
    bookmark: str
    # The paragraph under it, which the line numbers count.
    lead: str
    # The line that holds the abbreviation: what comes before it, the abbreviation, what
    # it stands for, and what comes after it.
    delivery: tuple[str, str, str, str]
    # The label set at the start of the lines, beside the aside.
    margin: str
    # The aside floated to the end of the lines.
    aside: str
    # The caption set before the table.
    caption: str
    # The table's header cells: the corner, the year, the two seasons.
    headers: tuple[str, str, str, str]
    # The table's two row headers.
    rows: tuple[str, str]
    # What stands before the redacted account number.
    account: str
    # The running head: the abbreviation, what it stands for, and the rest of the head's
    # title.
    head: tuple[str, str, str]
    # The word the ligature opens, after the ligature itself.
    ligature_rest: str
    # What the drawn tick is, in words.
    tick: str
    # A phrase in another language, and the code of that language.
    foreign: tuple[str, str]
    # The watermark across the first page.
    watermark: str
    # The page number, `{n}` standing for the page's own.
    page_number: str
    # The second page's title.
    lists_title: str
    # What an ordered list and an unordered one are called.
    ordered: tuple[str, str]
    # The two items every list holds.
    items: tuple[str, str]
    # What the description list's two terms mean.
    defined: tuple[str, str]
    # The third page's title, and the line under it.
    roles: tuple[str, str]


# The document in English.
ENGLISH = Words(
    lang="en",
    title="Notice of a paper delivery",
    bookmark="The deliveries, season by season",
    lead=(
        "This notice is a tagged document. The tree behind it says where each element "
        "stands, what it is for and what its abbreviations stand for, and every piece "
        "of furniture on the page says what kind of furniture it is, so that reading "
        "the notice aloud reads the notice and nothing else."
    ),
    delivery=(
        "Delivery in ",
        "approx.",
        "approximately",
        " three weeks.",
    ),
    margin="Note",
    aside="Prices hold until the end of the month.",
    caption="Quantities ordered, by season",
    headers=(
        "Item",
        "2026",
        "Spring",
        "Autumn",
    ),
    rows=(
        "Paper",
        "Ink",
    ),
    account="Account number:",
    head=(
        "Dept.",
        "Department",
        " of supplies ",
    ),
    ligature_rest="le 42",
    tick="A tick",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="COPY",
    page_number="Page {n} of 3",
    lists_title="The numbering a list can state",
    ordered=(
        "ordered",
        "unordered",
    ),
    items=(
        "Paper",
        "Ink",
    ),
    defined=(
        "sheets of 80 grams",
        "cartridges of one litre",
    ),
    roles=(
        "The roles an element can be given",
        (
            "Each name is written as the tree writes it, from the web's vocabulary and "
            "its publishing module."
        ),
    ),
)

# The document in French.
FRENCH = Words(
    lang="fr",
    title="Avis de livraison de papier",
    bookmark="Les livraisons, saison par saison",
    lead=(
        "Cet avis est un document balisé. L’arbre qui le décrit dit où se place chaque "
        "élément, à quoi il sert et ce que ses abréviations veulent dire, et chaque "
        "élément de décor de la page dit de quelle sorte il est : une lecture à voix "
        "haute restitue l’avis, et rien d’autre."
    ),
    delivery=(
        "Livraison sous ",
        "env.",
        "environ",
        " trois semaines.",
    ),
    margin="Note",
    aside="Les prix sont valables jusqu’à la fin du mois.",
    caption="Quantités commandées, par saison",
    headers=(
        "Article",
        "2026",
        "Printemps",
        "Automne",
    ),
    rows=(
        "Papier",
        "Encre",
    ),
    account="Numéro de compte :",
    head=(
        "Serv.",
        "Service",
        " des fournitures ",
    ),
    ligature_rest="chier 42",
    tick="Une coche",
    foreign=(
        "just in time",
        "en",
    ),
    watermark="COPIE",
    page_number="Page {n} sur 3",
    lists_title="La numérotation qu’une liste peut déclarer",
    ordered=(
        "ordonnée",
        "non ordonnée",
    ),
    items=(
        "Papier",
        "Encre",
    ),
    defined=(
        "feuilles de 80 grammes",
        "cartouches d’un litre",
    ),
    roles=(
        "Les rôles qu’un élément peut recevoir",
        (
            "Chaque nom est écrit comme l’arbre l’écrit, tiré du vocabulaire du web et "
            "de son module d’édition."
        ),
    ),
)

# The document in Dutch.
DUTCH = Words(
    lang="nl",
    title="Bericht van een papierlevering",
    bookmark="De leveringen, seizoen per seizoen",
    lead=(
        "Dit bericht is een getagd document. De boom erachter zegt waar elk element "
        "staat, waarvoor het dient en waar zijn afkortingen voor staan, en elk stuk "
        "meubilair op de pagina zegt wat voor meubilair het is, zodat het voorlezen "
        "van het bericht het bericht voorleest en niets anders."
    ),
    delivery=(
        "Levering over",
        "ong.",
        "ongeveer",
        " drie weken.",
    ),
    margin="Notitie",
    aside="De prijzen gelden tot het einde van de maand.",
    caption="Bestelde hoeveelheden, per seizoen",
    headers=(
        "Artikel",
        "2026",
        "Voorjaar",
        "Najaar",
    ),
    rows=(
        "Papier",
        "Inkt",
    ),
    account="Rekeningnummer:",
    head=(
        "Afd.",
        "Afdeling",
        " inkoop",
    ),
    ligature_rest="liaal 42",
    tick="Een vinkje",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="KOPIE",
    page_number="Pagina {n} van 3",
    lists_title="De nummering die een lijst kan noemen",
    ordered=(
        "genummerd",
        "ongenummerd",
    ),
    items=(
        "Papier",
        "Inkt",
    ),
    defined=(
        "vellen van 80 gram",
        "patronen van één liter",
    ),
    roles=(
        "De rollen die een element kan krijgen",
        (
            "Elke naam is geschreven zoals de boom hem schrijft, uit de woordenschat "
            "van het web en zijn publicatiemodule."
        ),
    ),
)

# The document in Portuguese.
PORTUGUESE = Words(
    lang="pt",
    title="Aviso de entrega de papel",
    bookmark="As entregas, estação a estação",
    lead=(
        "Este aviso é um documento etiquetado. A árvore por trás dele diz onde está "
        "cada elemento, para que serve e o que significam as suas abreviaturas, e "
        "cada peça de mobília da página diz que tipo de mobília é, para que ler o "
        "aviso em voz alta leia o aviso e nada mais."
    ),
    delivery=(
        "Entrega em",
        "aprox.",
        "aproximadamente",
        " três semanas.",
    ),
    margin="Nota",
    aside="Os preços mantêm-se até ao fim do mês.",
    caption="Quantidades encomendadas, por estação",
    headers=(
        "Artigo",
        "2026",
        "Primavera",
        "Outono",
    ),
    rows=(
        "Papel",
        "Tinta",
    ),
    account="Número de conta:",
    head=(
        "Serv.",
        "Serviço",
        " de fornecimentos",
    ),
    ligature_rest="lial 42",
    tick="Um visto",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="CÓPIA",
    page_number="Página {n} de 3",
    lists_title="A numeração que uma lista pode indicar",
    ordered=(
        "ordenada",
        "não ordenada",
    ),
    items=(
        "Papel",
        "Tinta",
    ),
    defined=(
        "folhas de 80 gramas",
        "cartuchos de um litro",
    ),
    roles=(
        "Os papéis que se podem dar a um elemento",
        (
            "Cada nome é escrito como a árvore o escreve, a partir do vocabulário da "
            "web e do seu módulo de publicação."
        ),
    ),
)

# The document in Italian.
ITALIAN = Words(
    lang="it",
    title="Avviso di consegna della carta",
    bookmark="Le consegne, stagione per stagione",
    lead=(
        "Questo avviso è un documento marcato. L’albero dietro di esso dice dove sta "
        "ogni elemento, a cosa serve e cosa significano le sue abbreviazioni, e ogni "
        "ornamento della pagina dice di che tipo è, così leggere l’avviso ad alta "
        "voce legge l’avviso e nient’altro."
    ),
    delivery=(
        "Consegna in",
        "circa",
        "approssimativamente",
        " tre settimane.",
    ),
    margin="Nota",
    aside="I prezzi valgono fino a fine mese.",
    caption="Quantità ordinate, per stagione",
    headers=(
        "Articolo",
        "2026",
        "Primavera",
        "Autunno",
    ),
    rows=(
        "Carta",
        "Inchiostro",
    ),
    account="Numero di conto:",
    head=(
        "Uff.",
        "Ufficio",
        " forniture",
    ),
    ligature_rest="liale 42",
    tick="Una spunta",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="COPIA",
    page_number="Pagina {n} di 3",
    lists_title="La numerazione che un elenco può indicare",
    ordered=(
        "ordinato",
        "non ordinato",
    ),
    items=(
        "Carta",
        "Inchiostro",
    ),
    defined=(
        "fogli da 80 grammi",
        "cartucce da un litro",
    ),
    roles=(
        "I ruoli che si possono dare a un elemento",
        (
            "Ogni nome è scritto come lo scrive l’albero, con il vocabolario del web "
            "e il suo modulo di pubblicazione."
        ),
    ),
)

# The document in Spanish.
SPANISH = Words(
    lang="es",
    title="Aviso de entrega de papel",
    bookmark="Las entregas, temporada a temporada",
    lead=(
        "Este aviso es un documento etiquetado. El árbol que tiene detrás dice dónde "
        "está cada elemento, para qué sirve y qué significan sus abreviaturas, y cada "
        "elemento decorativo de la página dice de qué tipo es, para que leer el aviso "
        "en voz alta lea el aviso y nada más."
    ),
    delivery=(
        "Entrega en",
        "aprox.",
        "aproximadamente",
        " tres semanas.",
    ),
    margin="Nota",
    aside="Los precios se mantienen hasta final de mes.",
    caption="Cantidades pedidas, por temporada",
    headers=(
        "Artículo",
        "2026",
        "Primavera",
        "Otoño",
    ),
    rows=(
        "Papel",
        "Tinta",
    ),
    account="Número de cuenta:",
    head=(
        "Serv.",
        "Servicio",
        " de suministros",
    ),
    ligature_rest="chero 42",
    tick="Una marca de verificación",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="COPIA",
    page_number="Página {n} de 3",
    lists_title="La numeración que puede indicar una lista",
    ordered=(
        "ordenada",
        "sin ordenar",
    ),
    items=(
        "Papel",
        "Tinta",
    ),
    defined=(
        "hojas de 80 gramos",
        "cartuchos de un litro",
    ),
    roles=(
        "Los papeles que puede recibir un elemento",
        (
            "Cada nombre se escribe como lo escribe el árbol, con el vocabulario de "
            "la web y su módulo de publicación."
        ),
    ),
)

# The document in German.
GERMAN = Words(
    lang="de",
    title="Mitteilung über eine Papierlieferung",
    bookmark="Die Lieferungen, Saison für Saison",
    lead=(
        "Diese Mitteilung ist ein getaggtes Dokument. Der Baum dahinter sagt, wo "
        "jedes Element steht, wozu es dient und wofür seine Abkürzungen stehen, und "
        "jedes Stück Beiwerk auf der Seite sagt, welche Art von Beiwerk es ist, "
        "sodass beim Vorlesen die Mitteilung vorgelesen wird und sonst nichts."
    ),
    delivery=(
        "Lieferung in ",
        "ca.",
        "circa",
        " drei Wochen.",
    ),
    margin="Hinweis",
    aside="Die Preise gelten bis Monatsende.",
    caption="Bestellte Mengen, nach Saison",
    headers=(
        "Artikel",
        "2026",
        "Frühjahr",
        "Herbst",
    ),
    rows=(
        "Papier",
        "Tinte",
    ),
    account="Kontonummer:",
    head=(
        "Abt.",
        "Abteilung",
        " Beschaffung ",
    ),
    ligature_rest="liale 42",
    tick="Ein Häkchen",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="KOPIE",
    page_number="Seite {n} von 3",
    lists_title="Die Nummerierung, die eine Liste angeben kann",
    ordered=(
        "geordnet",
        "ungeordnet",
    ),
    items=(
        "Papier",
        "Tinte",
    ),
    defined=(
        "Bögen zu 80 Gramm",
        "Patronen zu einem Liter",
    ),
    roles=(
        "Die Rollen, die ein Element erhalten kann",
        (
            "Jeder Name ist so geschrieben, wie der Baum ihn schreibt, aus dem "
            "Vokabular des Webs und seinem Publikationsmodul."
        ),
    ),
)

# 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 text(content, font, size, at, line):
    """Draw one line of text with its baseline at `at`."""
    content.draw_text(font, size, at[0], at[1], line)


def tagged(content, font, tag, mcid, at, line):
    """Draw one line of text as a run of content numbered `mcid` under `tag`."""
    content.begin_tagged(tag, mcid)
    text(content, font, BODY[0], at, line)
    content.end_marked()


def furniture(content, font, words, index):
    """Draw the furniture every page carries: a background, the running head, the
    trimmer's marks, the page number and the Bates number.

    The running head holds four runs that carry facts of their own rather than facts an
    element of the tree gives them.
    """
    page = hqf_pdf.Rect(0.0, 0.0, 595.0, 842.0)
    every_edge = [
        hqf_pdf.PageEdge.Top,
        hqf_pdf.PageEdge.Bottom,
        hqf_pdf.PageEdge.Left,
        hqf_pdf.PageEdge.Right,
    ]

    content.begin_artifact_placed(
        hqf_pdf.Artifact.Background, attached=every_edge, bbox=page
    )
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.99, 0.98, 0.95))
    content.rect(20.0, 20.0, 555.0, 802.0)
    content.fill()
    content.restore_state()
    content.end_marked()

    # The running head: a rule, and a line of runs each carrying its facts.
    content.begin_artifact_placed(
        hqf_pdf.Artifact.Pagination,
        attached=[hqf_pdf.PageEdge.Top],
        bbox=hqf_pdf.Rect(LEFT, 790.0, 395.0, 16.0),
    )
    content.rect(LEFT, 788.0, 395.0, 0.5)
    content.fill()
    size = 8.0
    x = LEFT
    pieces = (
        ({"expansion": words.head[1]}, words.head[0]),
        ({}, words.head[2]),
        ({"actual_text": "fi"}, "ﬁ"),
    )
    for facts, piece in pieces:
        content.begin_described(**facts)
        text(content, font, size, (x, 794.0), piece)
        content.end_marked()
        x += font.measure(piece, size)
    text(content, font, size, (x, 794.0), words.ligature_rest)
    x += font.measure(words.ligature_rest, size) + 12.0

    # A tick drawn as two strokes, which no font says: its facts say what it is.
    content.begin_described(alternate=words.tick)
    content.save_state()
    content.set_line_width(1.2)
    content.move_to(x, 797.0)
    content.line_to(x + 3.0, 794.0)
    content.line_to(x + 9.0, 801.0)
    content.stroke()
    content.restore_state()
    content.end_marked()
    x += 22.0

    content.begin_described(language=words.foreign[1])
    text(content, font, size, (x, 794.0), words.foreign[0])
    content.end_marked()
    content.end_marked()

    # The marks a trimmer cuts to, marked as belonging to the sheet rather than to the
    # page's content, and grouped under a tag of their own.
    content.begin_artifact(hqf_pdf.Artifact.Page)
    content.begin_marked("TrimMarks")
    content.save_state()
    content.set_line_width(0.3)
    for mark_x, mark_y, dx, dy in (
        (10.0, 20.0, 8.0, 0.0),
        (20.0, 10.0, 0.0, 8.0),
        (577.0, 20.0, 8.0, 0.0),
        (575.0, 10.0, 0.0, 8.0),
        (10.0, 822.0, 8.0, 0.0),
        (20.0, 824.0, 0.0, 8.0),
        (577.0, 822.0, 8.0, 0.0),
        (575.0, 824.0, 0.0, 8.0),
    ):
        content.move_to(mark_x, mark_y)
        content.line_to(mark_x + dx, mark_y + dy)
        content.stroke()
    content.restore_state()
    content.end_marked()
    content.end_marked()

    number = words.page_number.replace("{n}", str(index + 1))
    content.begin_artifact_placed(
        hqf_pdf.Artifact.PageNumber, attached=[hqf_pdf.PageEdge.Bottom]
    )
    text(content, font, size, (270.0, 40.0), number)
    content.end_marked()

    bates = FIRST_BATES + index
    content.begin_artifact_placed(
        hqf_pdf.Artifact.Bates,
        attached=[hqf_pdf.PageEdge.Bottom, hqf_pdf.PageEdge.Right],
        bbox=hqf_pdf.Rect(470.0, 36.0, 80.0, 12.0),
    )
    text(content, font, size, (470.0, 40.0), f"HQF-{bates:06d}")
    content.end_marked()


def notice(content, font, words):
    """Draw the notice, and hand back the branch of the tree describing it."""
    marks = hqf_pdf.Marks()
    children = []

    # The watermark across the page.
    content.begin_artifact(hqf_pdf.Artifact.Watermark)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.9))
    content.rotate(0.6, 297.5, 421.0)
    text(content, font, 110.0, (110.0, 380.0), words.watermark)
    content.restore_state()
    content.end_marked()

    mcid = marks.next_id()
    content.begin_tagged("H1", mcid)
    text(content, font, 18.0, (LEFT, 740.0), words.title)
    content.end_marked()
    children.append(
        hqf_pdf.StructElement(
            "H1", placement=hqf_pdf.Placement.Block, children=[(0, mcid)]
        )
    )

    # The paragraph the line numbers count, one run for the whole of it. Its first
    # baseline stands one leading under the top, where the numbers beside it start.
    flow = hqf_pdf.TextFlow(
        font,
        BODY[0],
        leading=BODY[1],
        first_baseline=hqf_pdf.FirstBaseline.leading(),
    )
    lines = flow.break_lines(words.lead, WIDTH)
    mcid = marks.next_id()
    content.begin_tagged("P", mcid)
    flow.draw(content, lines, LEFT, 712.0, WIDTH)
    content.end_marked()
    children.append(hqf_pdf.StructElement("P", children=[(0, mcid)]))

    content.begin_artifact_placed(
        hqf_pdf.Artifact.LineNumber, attached=[hqf_pdf.PageEdge.Left]
    )
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.5))
    baseline = 712.0 - BODY[1]
    for number in range(1, len(lines) + 1):
        text(content, font, 7.0, (70.0, baseline), str(number))
        baseline -= BODY[1]
    content.restore_state()
    content.end_marked()

    # The line holding the abbreviation, the abbreviation an element of its own, set
    # inline, that says what it stands for.
    top = baseline - 10.0
    before, short, long, after = words.delivery
    first = marks.next_id()
    tagged(content, font, "P", first, (LEFT, top), before)
    x = LEFT + font.measure(before, BODY[0])
    abbreviation = marks.next_id()
    tagged(content, font, "Span", abbreviation, (x, top), short)
    x += font.measure(short, BODY[0])
    last = marks.next_id()
    tagged(content, font, "P", last, (x, top), after)
    children.append(
        hqf_pdf.StructElement(
            "P",
            children=[
                (0, first),
                hqf_pdf.StructElement(
                    "Span",
                    placement=hqf_pdf.Placement.Inline,
                    expansion=long,
                    children=[(0, abbreviation)],
                ),
                (0, last),
            ],
        )
    )

    # A label at the start of the lines and an aside at their end, both at the height of
    # the account line.
    account_at = top - 30.0
    mcid = marks.next_id()
    content.begin_tagged("Note", mcid)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.45))
    text(content, font, 8.0, (40.0, account_at), words.margin)
    content.restore_state()
    content.end_marked()
    children.append(
        hqf_pdf.StructElement(
            "Note",
            placement=hqf_pdf.Placement.Start,
            aria_role=hqf_pdf.AriaRole.Note,
            children=[(0, mcid)],
        )
    )

    mcid = marks.next_id()
    content.begin_tagged("Aside", mcid)
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.6))
    content.set_line_width(0.5)
    content.rect(450.0, account_at - 30.0, 110.0, 44.0)
    content.stroke()
    aside = hqf_pdf.TextFlow(font, 8.0, leading=11.0)
    aside_lines = aside.break_lines(words.aside, 100.0)
    aside.draw(content, aside_lines, 455.0, account_at, 100.0)
    content.restore_state()
    content.end_marked()
    children.append(
        hqf_pdf.StructElement(
            "Aside",
            placement=hqf_pdf.Placement.End,
            aria_role=hqf_pdf.AriaRole.Complementary,
            children=[(0, mcid)],
        )
    )

    # The account number, removed: what is left of it is a black box.
    mcid = marks.next_id()
    tagged(content, font, "P", mcid, (LEFT, account_at), words.account)
    children.append(hqf_pdf.StructElement("P", children=[(0, mcid)]))
    x = LEFT + font.measure(words.account, BODY[0]) + 6.0
    content.begin_artifact_placed(
        hqf_pdf.Artifact.Redaction,
        attached=[],
        bbox=hqf_pdf.Rect(x, account_at - 3.0, 120.0, 13.0),
    )
    content.rect(x, account_at - 3.0, 120.0, 13.0)
    content.fill()
    content.end_marked()

    # The caption before the table, then the table itself.
    caption_at = account_at - 60.0
    mcid = marks.next_id()
    tagged(content, font, "Caption", mcid, (LEFT, caption_at), words.caption)
    caption = hqf_pdf.StructElement(
        "Caption", placement=hqf_pdf.Placement.Before, children=[(0, mcid)]
    )
    drawn = table(content, font, words, marks, caption_at - 20.0)
    children += [caption, drawn]
    return hqf_pdf.StructElement(
        "Sect", aria_role=hqf_pdf.AriaRole.Main, children=children
    )


def table(content, font, words, marks, top):
    """Draw the table under `top`: a corner heading both its row and its column of
    headers, a year spanning two seasons, and two rows each under its own header.
    Every data cell names the headers it sits under."""
    columns = (LEFT, LEFT + 110.0, LEFT + 190.0, LEFT + 270.0)
    row_height = 20.0
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.6))
    content.set_line_width(0.5)
    content.rect(
        LEFT - 4.0, top - 4.0 * row_height + 14.0, 270.0 + 80.0, 4.0 * row_height
    )
    content.stroke()
    content.restore_state()

    corner, year, spring, autumn = words.headers

    def cell(tag, at, line):
        mcid = marks.next_id()
        tagged(content, font, tag, mcid, at, line)
        return mcid

    corner_id = cell("TH", (columns[0], top), corner)
    year_id = cell("TH", (columns[1], top), year)
    spring_id = cell("TH", (columns[1], top - row_height), spring)
    autumn_id = cell("TH", (columns[2], top - row_height), autumn)
    header = hqf_pdf.StructElement(
        "THead",
        children=[
            hqf_pdf.StructElement(
                "TR",
                children=[
                    hqf_pdf.StructElement(
                        "TH",
                        id="corner",
                        scope=hqf_pdf.Scope.Both,
                        row_span=2,
                        children=[(0, corner_id)],
                    ),
                    hqf_pdf.StructElement(
                        "TH",
                        id="year",
                        scope=hqf_pdf.Scope.Column,
                        col_span=2,
                        children=[(0, year_id)],
                    ),
                ],
            ),
            hqf_pdf.StructElement(
                "TR",
                children=[
                    hqf_pdf.StructElement(
                        "TH",
                        id="spring",
                        scope=hqf_pdf.Scope.Column,
                        headers=["year"],
                        children=[(0, spring_id)],
                    ),
                    hqf_pdf.StructElement(
                        "TH",
                        id="autumn",
                        scope=hqf_pdf.Scope.Column,
                        headers=["year"],
                        children=[(0, autumn_id)],
                    ),
                ],
            ),
        ],
    )

    rows = []
    y = top - 2.0 * row_height
    for index, (name, counts) in enumerate(zip(words.rows, COUNTS)):
        row_id = f"row{index}"
        name_id = cell("TH", (columns[0], y), name)
        cells = [
            hqf_pdf.StructElement(
                "TH",
                id=row_id,
                scope=hqf_pdf.Scope.Row,
                headers=["corner"],
                children=[(0, name_id)],
            )
        ]
        for count, column, season in zip(counts, columns[1:], ("spring", "autumn")):
            mcid = cell("TD", (column, y), count)
            cells.append(
                hqf_pdf.StructElement(
                    "TD", headers=[row_id, season, "year"], children=[(0, mcid)]
                )
            )
        rows.append(hqf_pdf.StructElement("TR", children=cells))
        y -= row_height
    return hqf_pdf.StructElement(
        "Table",
        aria_role=hqf_pdf.AriaRole.Table,
        children=[header, hqf_pdf.StructElement("TBody", children=rows)],
    )


def lists(content, font, words):
    """Draw a list for each numbering a list can state, and hand back the branch of
    the tree describing them."""
    marks = hqf_pdf.Marks()
    mcid = marks.next_id()
    content.begin_tagged("H1", mcid)
    text(content, font, 18.0, (LEFT, 740.0), words.lists_title)
    content.end_marked()
    children = [hqf_pdf.StructElement("H1", children=[(1, mcid)])]

    for place, (numbering, labels) in enumerate(NUMBERINGS):
        column = LEFT if place % 2 == 0 else LEFT + 210.0
        top = 700.0 - (place // 2) * 100.0
        kind = words.ordered[0] if numbering.is_ordered() else words.ordered[1]
        mcid = marks.next_id()
        tagged(
            content,
            font,
            "Caption",
            mcid,
            (column, top),
            f"{numbering.as_str()}, {kind}",
        )
        entries = [hqf_pdf.StructElement("Caption", children=[(1, mcid)])]
        y = top - 18.0
        for item, defined, label in zip(words.items, words.defined, labels):
            if numbering == hqf_pdf.ListNumbering.Description:
                term = marks.next_id()
                tagged(content, font, "Lbl", term, (column + 12.0, y), item)
                meaning = marks.next_id()
                tagged(content, font, "LBody", meaning, (column + 60.0, y), defined)
                parts = [
                    hqf_pdf.StructElement("Lbl", children=[(1, term)]),
                    hqf_pdf.StructElement("LBody", children=[(1, meaning)]),
                ]
            else:
                parts = []
                if label:
                    numbered = marks.next_id()
                    tagged(content, font, "Lbl", numbered, (column + 12.0, y), label)
                    parts.append(hqf_pdf.StructElement("Lbl", children=[(1, numbered)]))
                said = marks.next_id()
                tagged(content, font, "LBody", said, (column + 36.0, y), item)
                parts.append(hqf_pdf.StructElement("LBody", children=[(1, said)]))
            entries.append(hqf_pdf.StructElement("LI", children=parts))
            y -= 16.0
        children.append(
            hqf_pdf.StructElement("L", list_numbering=numbering, children=entries)
        )
    return hqf_pdf.StructElement("Sect", children=children)


def roles(content, font, words):
    """Name every role an element can be given, four columns of them, and hand back
    the branch of the tree describing the page."""
    marks = hqf_pdf.Marks()
    heading = marks.next_id()
    content.begin_tagged("H1", heading)
    text(content, font, 18.0, (LEFT, 740.0), words.roles[0])
    content.end_marked()
    lead = marks.next_id()
    content.begin_tagged("P", lead)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    flow = hqf_pdf.TextFlow(font, 9.0, leading=12.0)
    lines = flow.break_lines(words.roles[1], 420.0)
    flow.draw(content, lines, LEFT, 718.0, 420.0)
    content.restore_state()
    content.end_marked()

    entries = []
    per_column = (len(ROLES) + 3) // 4
    for place, role in enumerate(ROLES):
        x = 60.0 + (place // per_column) * 115.0
        y = 660.0 - (place % per_column) * 21.0
        mcid = marks.next_id()
        content.begin_tagged("LBody", mcid)
        text(content, font, 7.5, (x, y), role.as_str())
        content.end_marked()
        entries.append(
            hqf_pdf.StructElement(
                "LI", children=[hqf_pdf.StructElement("LBody", children=[(2, mcid)])]
            )
        )
    return hqf_pdf.StructElement(
        "Sect",
        children=[
            hqf_pdf.StructElement("H1", children=[(2, heading)]),
            hqf_pdf.StructElement("P", children=[(2, lead)]),
            hqf_pdf.StructElement(
                "L",
                list_numbering=hqf_pdf.ListNumbering.NoNumbering,
                children=entries,
            ),
        ],
    )


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("tagged_structure.pdf", language)).stem
    )

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_version(hqf_pdf.Version.V2_0)
    document.set_info("Title", words.title)
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    branches = []
    for index, build in enumerate((notice, lists, roles)):
        content = hqf_pdf.Content()
        furniture(content, font, words, index)
        branches.append(build(content, font, words))
        page = hqf_pdf.Page.a4()
        page.set_content(content)
        document.add_page(page)
    document.set_structure(
        hqf_pdf.StructureTree(
            lang=words.lang,
            children=[hqf_pdf.StructElement("Document", children=branches)],
        )
    )
    # The bookmark leads to the element that heads the seasons, not to a spot on the
    # page: a reader follows the element wherever it is laid out.
    document.add_bookmark(hqf_pdf.Bookmark(words.bookmark, 0).tied_to("year"))

    written = document.write(out)
    print(f"wrote {out}: {written} bytes")


if __name__ == "__main__":
    main()
