"""Marks what has to come out of a statement before it is released.

The Python twin of the `write_redaction` example in Rust. A redaction is a mark, and
only a mark. It states which part of the page must go, what is to be shown in its
place, and what colour fills the gap — and all three describe the page as it will be
once a reading software has applied the mark and written the document out again.
Until then the words are still in the file under the box, and a search finds them.
That is the mistake this page is laid out to make visible.

The upper half is the statement as it is released: the entries readable, each under a
mark that covers exactly the words it hides, because every box is measured off the
line it stands on rather than guessed.

Under the statement, one line carries the five marks a reviewer lays on a passage
without asking for anything to go: each word is highlighted, underlined, struck
through or squiggled under, as it says, and a caret in the last gap marks where the
last word is to be inserted. The patches are read off the laid-out line, never
measured by hand. The reviewer has also circled the line's label freehand, with an
arrow to the line, and left a sticky note at its end.

The lower half is drawn by this example, in its own ink, to show what those three
redactions ask for. The first shows a word in the middle of the gap. The second
repeats it along the whole width. The third shows nothing at all.

The second page lays every other kind of mark, each carrying a name, flags that keep it
on the paper, a layer of its own, a border, an action when it is clicked and another
when the pointer comes onto it and leaves it: a box with a dashed border, a ring the
mark draws itself, lines ending eight other ways, an area, a run, a note under each of
six icons, a file pinned under three, a stroke by hand, a caret, an underline and a
redaction over two areas, the last two read back for what they hold.

Usage: python examples/write_redaction.py [out.pdf]
       HQF_PDF_LANG=fr python examples/write_redaction.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The margin the page is laid out inside.
MARGIN = 56.0

# How far the page runs across, between the margins.
WIDTH = 483.0

# How far the value of an entry stands from the margin.
VALUE = 160.0

# The size the entries are set in.
SIZE = 11.0

# The size the word in a gap is set in.
SHOWN_SIZE = 9.0

# How far a mark reaches above and below the baseline of the line it covers.
OVER = 3.0
UNDER = 3.0

# The most copies of a word one gap is filled with.
MOST_COPIES = 64

# Where each entry's baseline sits, as released.
ROWS = (700.0, 676.0, 652.0)

# Where each gap's baseline sits, in the half drawn to show what the marks ask for.
SHOWN_ROWS = (486.0, 462.0, 438.0)

# Where the box of the line carrying the five review marks starts, from the top.
REVIEW_TOP = 562.0

# The side of the square a sticky note's icon is drawn in.
NOTE = 20.0

# The loop drawn freehand around the review line's label, as offsets on an ellipse of
# unit half-axes centred on the label, in the order the pen went.
LOOP = (
    (-1.0, 0.1),
    (-0.92, -0.55),
    (-0.6, -0.95),
    (0.0, -1.08),
    (0.62, -0.97),
    (0.97, -0.5),
    (1.04, 0.12),
    (0.9, 0.66),
    (0.5, 1.0),
    (-0.05, 1.06),
    (-0.6, 0.92),
    (-0.95, 0.48),
    (-1.06, -0.08),
)

# The colour a highlight is painted in.
HIGHLIGHT = hqf_pdf.Rgb(1.0, 0.85, 0.2)

# The colour the three stroked marks are drawn in.
REVIEW_INK = hqf_pdf.Rgb(0.75, 0.1, 0.1)

# What each entry states. None of it is anybody's: the statement is written for this
# page.
ENTRIES = (
    "Claire Vasseur",
    "14 rue des Lilas, 59000 Lille",
    "FR76 3000 1007 9412 3456 7890 185",
)


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

    # The line at the head of the page.
    title: str
    # The heading over the statement as it is released.
    released: str
    # The heading over the half drawn to show what the marks ask for.
    applied: str
    # What each struck-out entry is called.
    labels: tuple[str, str, str]
    # What the line carrying the review marks is called.
    review: str
    # The five words of that line, each naming the mark it carries: the highlight, the
    # underline, the strike-out, the squiggle and the caret before the last word.
    marked: tuple[str, str, str, str, str]
    # What the loop drawn freehand around the review line's label says.
    circled: str
    # What the sticky note at the end of the review line says.
    note: str
    # The word shown in the first gap, and repeated along the second.
    shown: str
    # The paragraph the statement is released with.
    body: str
    # The line under it all.
    caption: str
    # The second page's title, and the paragraph under it.
    marks_title: str
    marks_lead: str
    # The name of the layer the marks of the second page belong to.
    layer: str
    # What the attached file is, told to the reader.
    attachment: str
    # What each row of the second page shows. `{dash}`, `{style}`, `{areas}` and
    # `{shows}` stand for what is read back from the mark.
    rows: tuple[str, ...]
    # The word the underline of the second page is laid under.
    sample: str
    # What each style of text mark is called: highlight, underline, strike-out,
    # squiggle.
    styles: tuple[str, str, str, str]
    # What a redaction that shows no words shows.
    nothing: str
    # The words the remark of the last row lays in its box.
    remark: str


# The page in English.
ENGLISH = Words(
    title="Witness statement, released in part",
    released="As it is released",
    applied="As a reading software shows it once it has applied the marks",
    labels=(
        "Name",
        "Address",
        "Account",
    ),
    review="Review",
    marked=(
        "highlighted",
        "underlined",
        "struck",
        "squiggled",
        "inserted",
    ),
    circled="circled by hand",
    note="None of these five marks asks for anything to go.",
    shown="REDACTED",
    body=(
        "The statement itself is released whole. What identifies the witness is struck "
        "out above: the name shows the reason in the middle of its gap, the address "
        "repeats it along the length of a longer one, and the account is covered "
        "without a word."
    ),
    caption=(
        "A mark says what must go. It does not take it out. Until a reading software "
        "applies these marks and writes the document out again, the words are still "
        "under the boxes and a search finds them — which is why the lower half is "
        "drawn here in this example's own ink, and is not what the file states."
    ),
    marks_title="What else a mark can carry",
    marks_lead=(
        "Each mark below carries a name, flags that decide where it shows, a layer of "
        "its own, a border, and something to do when it is clicked or pointed at."
    ),
    layer="Review",
    attachment="The statement, as a file",
    rows=(
        "A box with a dashed border, dash {dash}",
        "A ring the mark draws itself",
        "Lines ending eight other ways",
        "An area that goes to the first page",
        "A run that answers the pointer",
        "Six note icons, the first left open",
        "A file pinned under three icons",
        "A stroke by hand",
        "A caret where a paragraph begins",
        "A mark read back: {style}, {areas} area",
        "A redaction over {areas} areas, showing {shows}",
        "Words laid in a box of their own",
    ),
    sample="sample",
    styles=(
        "highlight",
        "underline",
        "strike-out",
        "squiggle",
    ),
    nothing="nothing",
    remark="Totals to check against the delivery note",
)

# The page in French.
FRENCH = Words(
    title="Déposition de témoin, communiquée en partie",
    released="Telle qu’elle est communiquée",
    applied=(
        "Telle qu’un logiciel de lecture l’affiche une fois les marques appliquées"
    ),
    labels=(
        "Nom",
        "Adresse",
        "Compte",
    ),
    review="Relecture",
    marked=(
        "surligné",
        "souligné",
        "barré",
        "ondulé",
        "inséré",
    ),
    circled="entouré à main levée",
    note="Aucune de ces cinq marques ne demande de retirer quoi que ce soit.",
    shown="CAVIARDÉ",
    body=(
        "La déposition elle-même est communiquée en entier. Ce qui identifie le "
        "témoin est caviardé ci-dessus : sur le nom, le motif figure au milieu de la "
        "zone masquée ; sur l’adresse, plus longue, il se répète d’un bout à "
        "l’autre ; le compte est masqué sans un mot."
    ),
    caption=(
        "Une marque dit ce qui doit disparaître. Elle ne l’enlève pas. Tant qu’un "
        "logiciel de lecture n’a pas appliqué ces marques et réécrit le document, les "
        "mots restent sous les marques et une recherche les trouve — c’est pourquoi "
        "la moitié inférieure est tracée ici avec l’encre propre de cet exemple : "
        "elle ne reflète pas le contenu du fichier."
    ),
    marks_title="Ce qu’une marque peut contenir d’autre",
    marks_lead=(
        "Chaque marque ci-dessous contient un nom, des indicateurs qui déterminent où "
        "elle s’affiche, son propre calque, une bordure et une action au clic ou au "
        "survol."
    ),
    layer="Relecture",
    attachment="La déposition sous forme de fichier",
    rows=(
        "Un cadre à bordure en tirets, motif {dash}",
        "Un anneau que la marque trace elle-même",
        "Des lignes terminées de huit autres façons",
        "Une zone qui mène à la première page",
        "Un tracé qui réagit au pointeur",
        "Six icônes de note, la première ouverte",
        "Un fichier joint sous trois icônes",
        "Un trait à main levée",
        "Un signe d’insertion en début de paragraphe",
        "Une marque lue : {style}, {areas} zone",
        "Un caviardage sur {areas} zones, texte affiché : {shows}",
        "Un texte posé dans son propre cadre",
    ),
    sample="exemple",
    styles=(
        "surlignage",
        "soulignement",
        "biffure",
        "soulignement ondulé",
    ),
    nothing="rien",
    remark="Totaux à rapprocher du bon de livraison",
)

# The page in Dutch.
DUTCH = Words(
    title="Getuigenverklaring, gedeeltelijk vrijgegeven",
    released="Zoals ze vrijgegeven wordt",
    applied="Zoals leessoftware haar toont nadat de markeringen zijn toegepast",
    labels=(
        "Naam",
        "Adres",
        "Rekening",
    ),
    review="Beoordeling",
    marked=(
        "gemarkeerd",
        "onderstreept",
        "doorgestreept",
        "gekronkeld",
        "ingevoegd",
    ),
    circled="met de hand omcirkeld",
    note="Geen van deze vijf markeringen vraagt dat er iets verdwijnt.",
    shown="WEGGELAKT",
    body=(
        "De verklaring zelf wordt volledig vrijgegeven. Wat de getuige identificeert, "
        "is hierboven weggelakt: de naam toont de reden midden in zijn gat, het adres "
        "herhaalt haar over de lengte van een langer gat, en de rekening wordt zonder "
        "een woord afgedekt."
    ),
    caption=(
        "Een markering zegt wat weg moet. Ze haalt het niet weg. Tot leessoftware "
        "deze markeringen toepast en het document opnieuw schrijft, staan de woorden "
        "nog onder de kaders en vindt een zoekopdracht ze; daarom is de onderste "
        "helft hier getekend in de eigen inkt van dit voorbeeld, en is ze niet wat "
        "het bestand vermeldt."
    ),
    marks_title="Wat een markering nog meer kan bevatten",
    marks_lead=(
        "Elke markering hieronder heeft een naam, vlaggen die bepalen waar ze te zien "
        "is, een eigen laag, een rand en iets om te doen als erop geklikt of gewezen "
        "wordt."
    ),
    layer="Beoordeling",
    attachment="De verklaring, als bestand",
    rows=(
        "Een kader met een streepjesrand, patroon {dash}",
        "Een ring die de markering zelf tekent",
        "Lijnen die op acht andere manieren eindigen",
        "Een gebied dat naar de eerste pagina leidt",
        "Een gebroken lijn die op de aanwijzer reageert",
        "Zes notitiepictogrammen, het eerste open",
        "Een bijgevoegd bestand onder drie pictogrammen",
        "Een lijn uit de vrije hand",
        "Een invoegteken waar een alinea begint",
        "Een uitgelezen markering: {style}, {areas} gebied",
        "Een weglating over {areas} gebieden, met {shows}",
        "Tekst in een eigen kader",
    ),
    sample="voorbeeld",
    styles=(
        "markering",
        "onderstreping",
        "doorhaling",
        "kronkellijn",
    ),
    nothing="niets",
    remark="Totalen vergelijken met de pakbon",
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Declaração de testemunha, divulgada em parte",
    released="Tal como é divulgada",
    applied="Como um programa de leitura a mostra depois de aplicar as marcas",
    labels=(
        "Nome",
        "Morada",
        "Conta",
    ),
    review="Revisão",
    marked=(
        "realçado",
        "sublinhado",
        "riscado",
        "ondulado",
        "inserido",
    ),
    circled="rodeado à mão",
    note="Nenhuma destas cinco marcas pede que se retire alguma coisa.",
    shown="RASURADO",
    body=(
        "A declaração é divulgada inteira. O que identifica a testemunha está riscado "
        "acima: o nome mostra o motivo no meio do seu espaço, a morada repete-o ao "
        "longo de um mais comprido, e a conta é tapada sem uma palavra."
    ),
    caption=(
        "Uma marca diz o que tem de sair. Não o retira. Até um programa de leitura "
        "aplicar estas marcas e voltar a escrever o documento, as palavras continuam "
        "por baixo das caixas e uma pesquisa encontra-as; é por isso que a metade de "
        "baixo é desenhada aqui com a tinta própria deste exemplo, e não é o que o "
        "ficheiro indica."
    ),
    marks_title="O que mais uma marca pode conter",
    marks_lead=(
        "Cada marca abaixo leva um nome, indicadores que decidem onde se vê, uma "
        "camada própria, um contorno e algo a fazer quando é clicada ou apontada."
    ),
    layer="Revisão",
    attachment="A declaração, como ficheiro",
    rows=(
        "Uma caixa de contorno tracejado, padrão {dash}",
        "Um círculo desenhado pela própria marca",
        "Linhas que acabam de outras oito formas",
        "Uma zona que leva à primeira página",
        "Uma linha quebrada que reage ao ponteiro",
        "Seis ícones de nota, o primeiro aberto",
        "Um ficheiro anexado a três ícones",
        "Um traço à mão livre",
        "Um sinal de inserção onde começa um parágrafo",
        "Uma marca relida: {style}, {areas} zona",
        "Uma rasura sobre {areas} zonas, à vista: {shows}",
        "Um texto numa caixa própria",
    ),
    sample="amostra",
    styles=(
        "realce",
        "sublinhado",
        "rasurado",
        "ondulado",
    ),
    nothing="nada",
    remark="Totais a conferir com a guia de remessa",
)

# The page in Italian.
ITALIAN = Words(
    title="Dichiarazione del testimone, pubblicata in parte",
    released="Come viene pubblicata",
    applied="Come la mostra un programma di lettura dopo aver applicato i segni",
    labels=(
        "Nome",
        "Indirizzo",
        "Conto",
    ),
    review="Revisione",
    marked=(
        "evidenziato",
        "sottolineato",
        "barrato",
        "ondulato",
        "inserito",
    ),
    circled="cerchiato a mano",
    note="Nessuno di questi cinque segni chiede di togliere qualcosa.",
    shown="OSCURATO",
    body=(
        "La dichiarazione è pubblicata per intero. Ciò che identifica il testimone è "
        "cancellato qui sopra: il nome mostra il motivo al centro del suo spazio, "
        "l’indirizzo lo ripete lungo uno più lungo, e il conto è coperto senza una "
        "parola."
    ),
    caption=(
        "Un segno dice cosa deve sparire. Non lo toglie. Finché un programma di "
        "lettura non applica questi segni e riscrive il documento, le parole sono "
        "ancora sotto i riquadri e una ricerca le trova; per questo la metà inferiore "
        "è disegnata qui con l’inchiostro proprio di questo esempio, e non è ciò che "
        "indica il file."
    ),
    marks_title="Cos’altro può contenere un segno",
    marks_lead=(
        "Ogni segno qui sotto porta un nome, indicatori che decidono dove si vede, un "
        "livello proprio, un bordo e qualcosa da fare quando lo si clicca o lo si "
        "punta."
    ),
    layer="Revisione",
    attachment="La dichiarazione, come file",
    rows=(
        "Un riquadro dal bordo tratteggiato, trattino {dash}",
        "Un anello che il segno disegna da sé",
        "Linee che finiscono in otto altri modi",
        "Una zona che porta alla prima pagina",
        "Una linea spezzata che reagisce al puntatore",
        "Sei icone di nota, la prima aperta",
        "Un file allegato sotto tre icone",
        "Un tratto a mano libera",
        "Un segno di inserimento dove inizia un paragrafo",
        "Un segno letto: {style}, {areas} zona",
        "Un oscuramento su {areas} zone, testo mostrato: {shows}",
        "Un testo in un riquadro tutto suo",
    ),
    sample="campione",
    styles=(
        "evidenziazione",
        "sottolineatura",
        "barratura",
        "ondulazione",
    ),
    nothing="nulla",
    remark="Totali da confrontare con il DDT",
)

# The page in Spanish.
SPANISH = Words(
    title="Declaración de testigo, publicada en parte",
    released="Tal como se publica",
    applied="Como la muestra un programa de lectura tras aplicar las marcas",
    labels=(
        "Nombre",
        "Dirección",
        "Cuenta",
    ),
    review="Revisión",
    marked=(
        "resaltado",
        "subrayado",
        "tachado",
        "ondulado",
        "insertado",
    ),
    circled="rodeado a mano",
    note="Ninguna de estas cinco marcas pide que se quite nada.",
    shown="CENSURADO",
    body=(
        "La declaración se publica entera. Lo que identifica al testigo está tapado "
        "arriba: el nombre muestra el motivo en medio de su hueco, la dirección lo "
        "repite a lo largo de uno más largo y la cuenta se tapa sin una palabra."
    ),
    caption=(
        "Una marca dice lo que debe quitarse. No lo quita. Hasta que un programa de "
        "lectura aplica estas marcas y vuelve a escribir el documento, las palabras "
        "siguen bajo las cajas y una búsqueda las encuentra; por eso la mitad "
        "inferior se dibuja aquí con la tinta propia de este ejemplo, y no es lo que "
        "indica el archivo."
    ),
    marks_title="Qué más puede llevar una marca",
    marks_lead=(
        "Cada marca de abajo lleva un nombre, indicadores que deciden dónde se ve, "
        "una capa propia, un borde y algo que hacer cuando se hace clic en ella o se "
        "pasa el puntero sobre ella."
    ),
    layer="Revisión",
    attachment="La declaración, como archivo",
    rows=(
        "Un recuadro de borde discontinuo, patrón {dash}",
        "Un círculo trazado por la propia marca",
        "Líneas que terminan de otras ocho formas",
        "Una zona que lleva a la primera página",
        "Una línea quebrada que responde al puntero",
        "Seis iconos de nota, el primero abierto",
        "Un mismo archivo adjunto a tres iconos",
        "Un trazo a mano alzada",
        "Un signo de intercalación donde empieza un párrafo",
        "Una marca leída: {style}, zonas: {areas}",
        "Zonas por censurar: {areas}; visible: {shows}",
        "Un texto en su propio recuadro",
    ),
    sample="muestra",
    styles=(
        "resaltado",
        "subrayado",
        "tachado",
        "ondulado",
    ),
    nothing="nada",
    remark="Totales que cotejar con el albarán",
)

# The page in German.
GERMAN = Words(
    title="Zeugenaussage, teilweise freigegeben",
    released="So, wie sie freigegeben wird",
    applied="So, wie eine Lesesoftware sie zeigt, nachdem sie die Markierungen angewandt hat",
    labels=(
        "Name",
        "Adresse",
        "Konto",
    ),
    review="Prüfung",
    marked=(
        "hervorgehoben",
        "unterstrichen",
        "durchgestrichen",
        "geschlängelt",
        "eingefügt",
    ),
    circled="von Hand umkreist",
    note="Keine dieser fünf Markierungen verlangt, dass etwas wegkommt.",
    shown="GESCHWÄRZT",
    body=(
        "Die Aussage selbst wird vollständig freigegeben. Was den Zeugen erkennbar "
        "macht, ist oben getilgt: Der Name zeigt den Grund in der Mitte seiner Lücke, "
        "die Adresse wiederholt ihn über eine längere Lücke, und das Konto wird "
        "wortlos abgedeckt."
    ),
    caption=(
        "Eine Markierung sagt, was wegmuss. Sie nimmt es nicht heraus. Bis eine "
        "Lesesoftware diese Markierungen anwendet und das Dokument neu schreibt, "
        "stehen die Wörter noch unter den Kästen, und eine Suche findet sie — darum "
        "ist die untere Hälfte hier mit der eigenen Farbe dieses Beispiels gezeichnet "
        "und nicht das, was die Datei angibt."
    ),
    marks_title="Was eine Markierung noch alles kann",
    marks_lead=(
        "Jede Markierung unten trägt einen Namen, Kennzeichen, die bestimmen, wo sie "
        "erscheint, eine eigene Ebene, einen Rahmen und etwas, das beim Klicken oder "
        "Zeigen geschieht."
    ),
    layer="Prüfung",
    attachment="Die Aussage, als Datei",
    rows=(
        "Gestrichelter Rahmen, Strichmuster {dash}",
        "Ring, den die Markierung selbst zeichnet",
        "Linien mit acht weiteren Endformen",
        "Bereich, der zur ersten Seite führt",
        "Linienzug, der auf den Mauszeiger reagiert",
        "Sechs Notizsymbole, das erste offen",
        "Datei, an drei Symbole angeheftet",
        "Freihandstrich",
        "Einfügezeichen am Absatzbeginn",
        "Ausgelesen: {style}, Bereiche: {areas}",
        "Schwärzung, Bereiche: {areas}, zeigt {shows}",
        "Text in eigenem Rahmen",
    ),
    sample="Muster",
    styles=(
        "Hervorhebung",
        "Unterstreichung",
        "Durchstreichung",
        "Schlängellinie",
    ),
    nothing="nichts",
    remark="Summen mit dem Lieferschein abgleichen",
)

# 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 fitting(room: float, one: float, step: float) -> int:
    """How many copies of a word `one` wide, set `step` apart, stand in `room`."""
    copies = 0
    while copies < MOST_COPIES and copies * step + one <= room:
        copies += 1
    return copies


def paragraph(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    top: float,
    color: hqf_pdf.Rgb,
    text: str,
) -> None:
    """Writes a paragraph in a column the width of the page."""
    flow = hqf_pdf.TextFlow(font, size, leading=size * 1.4, color=color)
    lines = flow.break_lines(text, WIDTH)
    flow.draw(content, lines, MARGIN, top, WIDTH)


def gap(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    y: float,
    width: float,
    shown: str,
    align: hqf_pdf.FieldAlign,
    repeating: bool,
) -> None:
    """Draws the gap a mark asks for: the colour it states, and the words it shows in
    it, set where its alignment puts them and repeated if it asks for that."""
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.0))
    content.rect(MARGIN + VALUE, y - UNDER, width, SIZE + OVER + UNDER)
    content.fill()

    if shown:
        content.set_fill(hqf_pdf.Rgb.gray(1.0))
        one = font.measure(shown, SHOWN_SIZE)
        step = one + font.measure("   ", SHOWN_SIZE)
        left = MARGIN + VALUE
        if align == hqf_pdf.FieldAlign.Center:
            start = (width - one) * 0.5 + left
        elif align == hqf_pdf.FieldAlign.Right:
            start = left + width - one
        else:
            start = left
        room = left + width - start
        times = fitting(room, one, step) if repeating else int(one <= room)
        for copy in range(times):
            content.draw_text(font, SHOWN_SIZE, copy * step + start, y, shown)
    content.restore_state()


# Where the marks of the second page stand, and how far each row stands under the one
# before.
MARK_X = 330.0
MARK_STEP = 52.0


def mark_name(row: int) -> str:
    """The name a mark of the second page carries, from its row."""
    return f"review-{row}"


def to_statement() -> hqf_pdf.Action:
    """What a mark of the second page does when it is clicked: going back to the
    statement."""
    return hqf_pdf.Action.to_page(0, hqf_pdf.PageFit.whole_page())


def pointed_at() -> hqf_pdf.WidgetTriggers:
    """What a mark of the second page does when the pointer comes onto it and leaves
    it."""
    return (
        hqf_pdf.WidgetTriggers()
        .enter(hqf_pdf.Action.menu_item(hqf_pdf.MenuItem.FirstPage))
        .exit(hqf_pdf.Action.menu_item(hqf_pdf.MenuItem.LastPage))
    )


def ring(x: float, y: float) -> hqf_pdf.Content:
    """A ring about (x, y) the mark draws itself, rather than one reading software
    draws from its border. An appearance is drawn in the page's own coordinates."""
    drawn = hqf_pdf.Content()
    drawn.set_stroke(REVIEW_INK)
    drawn.set_line_width(3.0)
    drawn.circle(x, y, 12.0)
    drawn.stroke()
    return drawn


def marks_page(document, font, words) -> hqf_pdf.Page:
    """The second page: every other mark, each carrying a name, flags, a layer, a
    border, and something to do when clicked or pointed at."""
    layer = document.add_layer(hqf_pdf.Layer(words.layer))
    file = document.attach(
        hqf_pdf.Attachment(
            "statement.txt",
            words.attachment,
            "text/plain",
            hqf_pdf.Relationship.Unspecified,
            "2026-09-17T09:00:00Z",
            ENTRIES[0].encode(),
        )
    )
    shown = hqf_pdf.AnnotationFlags.none().printed()
    dashed = hqf_pdf.AnnotationBorder.dashed(1.5, hqf_pdf.Dash.on_off(4.0, 2.0))
    dash = (
        ""
        if dashed.dash is None
        else " ".join(f"{length:.0f}" for length in dashed.dash.lengths)
    )
    thin = hqf_pdf.AnnotationBorder.solid(1.0)

    content = hqf_pdf.Content()
    content.draw_text(font, 16.0, MARGIN, 780.0, words.marks_title)
    paragraph(content, font, 9.0, 760.0, hqf_pdf.Rgb.gray(0.35), words.marks_lead)
    boxed = words.rows[0].replace("{dash}", dash)

    rows = [690.0 - row * MARK_STEP for row in range(12)]
    page = hqf_pdf.Page.a4()

    def common(mark, contents, row):
        return (
            mark.color(REVIEW_INK)
            .contents(contents)
            .name(mark_name(row))
            .layer(layer)
            .action(to_statement())
            .triggers(pointed_at())
        )

    # A box with a dashed border, drawn plain rather than as a cloud.
    page.add_annotation(
        common(
            hqf_pdf.SquareAnnotation(MARK_X, rows[0] - 8.0, 120.0, 26.0)
            .effect(hqf_pdf.BorderEffect.plain())
            .border(dashed)
            .flags(shown),
            boxed,
            0,
        )
    )

    # A ring the mark draws itself.
    page.add_annotation(
        common(
            hqf_pdf.CircleAnnotation(MARK_X, rows[1] - 10.0, 30.0, 30.0)
            .appearance(ring(MARK_X + 15.0, rows[1] + 5.0))
            .border(thin)
            .flags(shown.no_rotate()),
            words.rows[1],
            1,
        )
    )

    # Four lines, each ending two other ways.
    endings = (
        (hqf_pdf.LineEnding.Square, hqf_pdf.LineEnding.Circle),
        (hqf_pdf.LineEnding.Diamond, hqf_pdf.LineEnding.OpenArrow),
        (hqf_pdf.LineEnding.ROpenArrow, hqf_pdf.LineEnding.RClosedArrow),
        (hqf_pdf.LineEnding.Slash, hqf_pdf.LineEnding.Slash),
    )
    x = MARK_X
    for start, end in endings:
        page.add_annotation(
            common(
                hqf_pdf.LineAnnotation(x, rows[2] + 4.0, x + 40.0, rows[2] + 4.0)
                .endings(start, end)
                .interior(REVIEW_INK)
                .border(thin)
                .flags(shown),
                words.rows[2],
                2,
            )
        )
        x += 55.0

    # An area that goes to the first page when clicked.
    page.add_annotation(
        hqf_pdf.PolygonAnnotation(
            [
                (MARK_X, rows[3] - 8.0),
                (MARK_X + 60.0, rows[3] - 8.0),
                (MARK_X + 80.0, rows[3] + 14.0),
                (MARK_X + 20.0, rows[3] + 18.0),
            ]
        )
        .interior(hqf_pdf.Rgb(1.0, 0.9, 0.9))
        .border(thin)
        .color(REVIEW_INK)
        .contents(words.rows[3])
        .name(mark_name(3))
        .flags(shown)
        .layer(layer)
        .action(hqf_pdf.Action.menu_item(hqf_pdf.MenuItem.FirstPage))
        .triggers(pointed_at())
    )

    # A run that answers the pointer coming onto it and leaving it.
    page.add_annotation(
        common(
            hqf_pdf.PolyLineAnnotation(
                [
                    (MARK_X, rows[4]),
                    (MARK_X + 30.0, rows[4] + 12.0),
                    (MARK_X + 60.0, rows[4]),
                    (MARK_X + 90.0, rows[4] + 12.0),
                ]
            )
            .border(dashed)
            .flags(shown),
            words.rows[4],
            4,
        )
    )

    # Six notes, one per icon, the first left open.
    icons = (
        hqf_pdf.NoteIcon.Note,
        hqf_pdf.NoteIcon.Key,
        hqf_pdf.NoteIcon.Help,
        hqf_pdf.NoteIcon.NewParagraph,
        hqf_pdf.NoteIcon.Paragraph,
        hqf_pdf.NoteIcon.Insert,
    )
    x = MARK_X
    for place, icon in enumerate(icons):
        note = (
            hqf_pdf.StickyNoteAnnotation(x, rows[5] - 6.0, words.note)
            .icon(icon)
            .border(thin)
            .color(HIGHLIGHT)
            .name(mark_name(5))
            .flags(shown)
            .layer(layer)
            .action(to_statement())
            .triggers(pointed_at())
        )
        page.add_annotation(note.open() if place == 0 else note)
        x += 30.0

    # The same file pinned under three icons.
    x = MARK_X
    for icon in (
        hqf_pdf.AttachmentIcon.Graph,
        hqf_pdf.AttachmentIcon.PushPin,
        hqf_pdf.AttachmentIcon.Tag,
    ):
        page.add_annotation(
            common(
                hqf_pdf.FileAttachmentAnnotation(x, rows[6] - 6.0, file)
                .icon(icon)
                .border(thin)
                .flags(shown),
                words.attachment,
                6,
            )
        )
        x += 40.0

    # A stroke by hand.
    page.add_annotation(
        common(
            hqf_pdf.InkAnnotation(
                [
                    [
                        (MARK_X, rows[7]),
                        (MARK_X + 20.0, rows[7] + 10.0),
                        (MARK_X + 40.0, rows[7] - 4.0),
                        (MARK_X + 60.0, rows[7] + 8.0),
                    ]
                ]
            )
            .border(hqf_pdf.AnnotationBorder.solid(2.0))
            .flags(shown),
            words.rows[7],
            7,
        )
    )

    # A caret marking where a paragraph is to begin.
    page.add_annotation(
        common(
            hqf_pdf.CaretAnnotation(MARK_X, rows[8] - 4.0, 12.0, 12.0)
            .paragraph()
            .border(thin)
            .flags(shown),
            words.rows[8],
            8,
        )
    )

    # A word underlined, the mark read back for its style and its areas.
    sample_width = font.measure(words.sample, SIZE)
    content.draw_text(font, SIZE, MARK_X, rows[9], words.sample)
    patch = hqf_pdf.Rect(
        MARK_X, rows[9] - UNDER, sample_width, SIZE + OVER + UNDER
    ).quad()
    underline = common(
        hqf_pdf.TextMarkAnnotation.underline([patch]).border(thin).flags(shown),
        words.sample,
        9,
    )
    styles = (
        hqf_pdf.MarkStyle.Highlight,
        hqf_pdf.MarkStyle.Underline,
        hqf_pdf.MarkStyle.StrikeOut,
        hqf_pdf.MarkStyle.Squiggly,
    )
    style = next(
        name for known, name in zip(styles, words.styles) if underline.style == known
    )
    read_back = (
        words.rows[9]
        .replace("{style}", style)
        .replace("{areas}", str(len(underline.areas)))
    )
    page.add_annotation(underline)

    # A redaction over two areas, drawing its own overlay, read back for its areas and
    # for the words it shows.
    areas = [
        hqf_pdf.Rect(MARK_X, rows[10] - 4.0, 60.0, 14.0).quad(),
        hqf_pdf.Rect(MARK_X + 70.0, rows[10] - 4.0, 60.0, 14.0).quad(),
    ]
    overlay = hqf_pdf.Content()
    overlay.set_stroke(hqf_pdf.Rgb.gray(1.0))
    overlay.move_to(2.0, 2.0)
    overlay.line_to(56.0, 12.0)
    overlay.stroke()
    redaction = (
        hqf_pdf.RedactionAnnotation(MARK_X, rows[10] - 4.0, 130.0, 14.0)
        .over(areas)
        .fill(hqf_pdf.Rgb.gray(0.0))
        .overlay(overlay)
        .border(thin)
        .flags(shown)
    )
    shows = redaction.text if redaction.text is not None else words.nothing
    redacted = (
        words.rows[10]
        .replace("{areas}", str(len(redaction.areas)))
        .replace("{shows}", shows)
    )
    page.add_annotation(common(redaction, redacted, 10))

    # A remark laid in a box of its own, its text set by the library.
    remark = hqf_pdf.TextFlow(
        font, 9.0, color=REVIEW_INK, left_indent=4.0, right_indent=4.0
    )
    page.add_annotation(
        hqf_pdf.FreeTextAnnotation(
            MARK_X, rows[11] - 6.0, 200.0, 20.0, remark, words.remark
        )
        .border(thin)
        .color(REVIEW_INK)
        .name(mark_name(11))
        .flags(shown)
        .layer(layer)
        .action(to_statement())
        .triggers(pointed_at())
    )

    # The label of each row, some of them read back from the mark they name.
    for row, (at, label) in enumerate(zip(rows, words.rows)):
        line = {0: boxed, 9: read_back, 10: redacted}.get(row, label)
        content.draw_text(font, 9.5, MARGIN, at, line)

    page.set_content(content)
    return page


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.DEFAULT_FONT))

    widths = tuple(font.measure(entry, SIZE) for entry in ENTRIES)

    content = hqf_pdf.Content()
    content.draw_text(font, 16.0, MARGIN, 780.0, words.title)

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(font, 9.0, MARGIN, 736.0, words.released)
    content.draw_text(font, 9.0, MARGIN, 522.0, words.applied)
    content.restore_state()

    for row, label, entry in zip(ROWS, words.labels, ENTRIES):
        content.draw_text(font, SIZE, MARGIN, row, label)
        content.draw_text(font, SIZE, MARGIN + VALUE, row, entry)
    paragraph(content, font, 10.0, 618.0, hqf_pdf.Rgb.gray(0.0), words.body)

    # The review line: five words, each its own span, so each comes back as a box of its
    # own once the line is laid out.
    plain = hqf_pdf.Style(font, SIZE)
    first, second, third, fourth, fifth = words.marked
    review = (
        hqf_pdf.RichText()
        .span(first, plain)
        .span("   ", plain)
        .span(second, plain)
        .span("   ", plain)
        .span(third, plain)
        .span("   ", plain)
        .span(fourth, plain)
        .span("   ", plain)
        .span(fifth, plain)
    )
    reviewed = review.break_lines(WIDTH - VALUE)
    review.draw(content, reviewed, MARGIN + VALUE, REVIEW_TOP, WIDTH - VALUE)
    boxes = review.fragment_boxes(reviewed, MARGIN + VALUE, REVIEW_TOP, WIDTH - VALUE)
    # The label sits on the line's baseline, one line's height below its top.
    baseline = REVIEW_TOP - reviewed.height(0) if len(reviewed) else REVIEW_TOP - SIZE
    content.draw_text(font, SIZE, MARGIN, baseline, words.review)

    for row, label in zip(SHOWN_ROWS, words.labels):
        content.draw_text(font, SIZE, MARGIN, row, label)
    gap(
        content,
        font,
        SHOWN_ROWS[0],
        widths[0],
        words.shown,
        hqf_pdf.FieldAlign.Center,
        False,
    )
    gap(
        content,
        font,
        SHOWN_ROWS[1],
        widths[1],
        words.shown,
        hqf_pdf.FieldAlign.Left,
        True,
    )
    gap(content, font, SHOWN_ROWS[2], widths[2], "", hqf_pdf.FieldAlign.Left, False)

    paragraph(content, font, 8.5, 402.0, hqf_pdf.Rgb.gray(0.35), words.caption)

    page = hqf_pdf.Page.a4()
    page.set_content(content)

    # Each mark covers the words it hides and nothing else, so it is measured off the
    # line it stands on.
    marks = [
        hqf_pdf.RedactionAnnotation(
            MARGIN + VALUE, ROWS[struck] - UNDER, widths[struck], SIZE + OVER + UNDER
        ).fill(hqf_pdf.Rgb.gray(0.0))
        for struck in range(len(ENTRIES))
    ]
    page.add_annotation(
        marks[0].overlay_text(words.shown).aligned(hqf_pdf.FieldAlign.Center)
    )
    page.add_annotation(
        marks[1]
        .overlay_text(words.shown)
        .repeating(True)
        .aligned(hqf_pdf.FieldAlign.Left)
    )
    page.add_annotation(marks[2])

    # Each review mark covers its own word, read off the laid-out line.
    patches = [hqf_pdf.Quad.of_rect(rect) for line in boxes for rect in line]
    if len(patches) != len(words.marked):
        raise ValueError("the review line is laid out as five words")
    highlighted, underlined, struck, squiggled, inserted = patches
    page.add_annotation(
        hqf_pdf.TextMarkAnnotation.highlight([highlighted], HIGHLIGHT).contents(
            words.marked[0]
        )
    )
    page.add_annotation(
        hqf_pdf.TextMarkAnnotation.underline([underlined])
        .color(REVIEW_INK)
        .contents(words.marked[1])
    )
    page.add_annotation(
        hqf_pdf.TextMarkAnnotation.strike_out([struck])
        .color(REVIEW_INK)
        .contents(words.marked[2])
    )
    page.add_annotation(
        hqf_pdf.TextMarkAnnotation.squiggly([squiggled])
        .color(REVIEW_INK)
        .contents(words.marked[3])
    )
    # The caret is centred on the gap before the last word, its point on the line. The
    # gap runs from the right edge of the upright box around the patch before it to the
    # lower left corner of the patch after it.
    before = squiggled.bounds()
    gap_start = before.x + before.width
    gap_end, foot = inserted.corners[0]
    page.add_annotation(
        hqf_pdf.CaretAnnotation((gap_start + gap_end) / 2.0 - 4.0, foot - 3.0, 8.0, 8.0)
        .color(REVIEW_INK)
        .inset(1.0, 0.0, 1.0, 0.0)
        .contents(words.marked[4])
    )

    # What the reviewer adds by hand: a loop around the label, with an arrow from it to
    # the line, all in one scribble of three strokes; and a sticky note at the line's
    # end.
    label = font.measure(words.review, SIZE)
    cx, cy = MARGIN + label / 2.0, baseline + 3.5
    rx, ry = label / 2.0 + 7.0, 10.0
    circle = [(cx + dx * rx, cy + dy * ry) for dx, dy in LOOP]
    tip = MARGIN + VALUE - 8.0
    tail = cx + rx + 3.0
    arrow = [(tail, cy), ((tail + tip) / 2.0, cy + 2.0), (tip, cy)]
    head = [(tip - 5.0, cy + 4.0), (tip, cy), (tip - 5.0, cy - 4.0)]
    page.add_annotation(
        hqf_pdf.InkAnnotation([circle, arrow, head])
        .color(REVIEW_INK)
        .contents(words.circled)
    )
    page.add_annotation(
        hqf_pdf.StickyNoteAnnotation(MARGIN + WIDTH - NOTE, baseline - 6.0, words.note)
        .icon(hqf_pdf.NoteIcon.Comment)
        .color(HIGHLIGHT)
    )

    document.add_page(page)
    document.add_page(marks_page(document, font, words))

    written = document.write(out)
    print(f"wrote {out}: {written} bytes, {len(ENTRIES)} entries struck out")


if __name__ == "__main__":
    main()
