"""Writes three customer statements into one file, and says in the file where each of
them starts.

The Python twin of the `write_document_parts` example in Rust. A print shop that
receives a single PDF of four sheets has no way of knowing that it holds three
statements rather than one long one, nor how many copies each recipient is owed. That
is what a job ticket beside the file is usually for. Here the file says it itself: a
hierarchy of document parts, one part per statement, each claiming its own run of
pages, stating what a press needs to know about it, and carrying the data file that
belongs to it.

What a part states takes every kind of value a part can hold: text, a whole number, a
real number, a date, a yes or no, a list, and a set of fields of its own. A flag that
only steers the preview is set while the part is put together and taken out before it
is written.

The foot of every sheet is a link to the part of the file its statement is: clicked,
it leads to that statement's first sheet.

Both sets of words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf


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

    # What the file as a whole is called.
    title: str
    # What the file carries, said once at the top of the first sheet.
    lead: str
    # What the hierarchy says, said in grey at the foot of the first sheet.
    note: str
    # The word a statement is called by.
    statement: str
    # The word a customer number is introduced by.
    customer: str
    # The word a sheet is counted by.
    sheet: str
    # Who each of the three statements is for.
    recipients: tuple[str, str, str]
    # Where each of them is sent.
    towns: tuple[str, str, str]
    # The country every recipient is in.
    country: str
    # The two column headings of a statement.
    columns: tuple[str, str]
    # What the three lines of a statement are called.
    lines: tuple[str, str, str]
    # The label on the total row.
    total: str
    # The heading of the terms sheet.
    terms_title: str
    # What the terms sheet says.
    terms: str
    # What the file carried beside each statement holds.
    carried: str


# The pages in English.
ENGLISH = Words(
    title="Three statements, one file",
    lead=(
        "The four sheets below are three statements, not one. Nothing drawn on them "
        "says where one recipient ends and the next begins — the file says it, beside "
        "the pages rather than on them, so a press can print and cut this run without "
        "a second file explaining it."
    ),
    note=(
        "Each part claims its own run of sheets, states the customer it is for and "
        "the number of copies owed, and carries the data file that belongs to it and "
        "to no other part. Reading software shows one document; a press reads three."
    ),
    statement="Statement",
    customer="Customer",
    sheet="Sheet",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="United Kingdom",
    columns=("Description", "Amount"),
    lines=(
        "Goods delivered in July",
        "Carriage, four crates",
        "Storage, one month",
    ),
    total="Total",
    terms_title="Terms of payment",
    terms=(
        "Payment falls due thirty days from the date this statement was posted. An "
        "amount still owing after that date carries interest at three times the legal "
        "rate, and a fixed sum of forty euros towards the cost of recovering it. "
        "Payment is made to the account named on the statement, quoting the customer "
        "number."
    ),
    carried="The statement as a data file",
)

# The pages in French.
FRENCH = Words(
    title="Trois relevés, un seul fichier",
    lead=(
        ("Les quatre feuillets ci-dessous forment trois relevés, et non un seul. Rien "
         "de ce qui y est imprimé ne dit où finit un destinataire et où commence le "
         "suivant : c’est le fichier qui le dit, à côté des pages et non sur elles, si"
         " bien qu’un imprimeur peut tirer et couper ce lot sans un second fichier "
         "pour le lui expliquer.")
    ),
    note=(
        ("Chaque partie délimite sa propre suite de feuillets, indique le client "
         "auquel elle est destinée et le nombre d’exemplaires dus, et contient le "
         "fichier de données qui n’appartient qu’à elle. Un logiciel de lecture "
         "affiche un document ; un imprimeur en lit trois.")
    ),
    statement="Relevé",
    customer="Client",
    sheet="Feuillet",
    recipients=(
        "Boulangerie Petit",
        "Menuiserie Vallon",
        "Laiterie du Coteau",
    ),
    towns=("Aix-en-Provence", "Annecy", "Quimper"),
    country="France",
    columns=("Désignation", "Montant"),
    lines=(
        "Marchandises livrées en juillet",
        "Transport, quatre caisses",
        "Entreposage, un mois",
    ),
    total="Total",
    terms_title="Conditions de règlement",
    terms=(
        ("Le règlement est exigible trente jours après la date d’envoi du présent "
         "relevé. Toute somme encore due passé cette date donne lieu à des intérêts au"
         " triple du taux légal, ainsi qu’à une indemnité forfaitaire de quarante "
         "euros pour frais de recouvrement. Le règlement s’effectue sur le compte "
         "indiqué sur le relevé, en rappelant le numéro de client.")
    ),
    carried="Le relevé sous forme de fichier de données",
)

# The pages in Dutch.
DUTCH = Words(
    title="Drie afschriften, één bestand",
    lead=(
        "De vier bladen hieronder zijn drie afschriften, niet één. Niets wat erop "
        "getekend is, zegt waar de ene ontvanger ophoudt en de volgende begint: het "
        "bestand zegt het, naast de pagina’s in plaats van erop, zodat een drukkerij "
        "deze oplage kan drukken en snijden zonder een tweede bestand dat het uitlegt."
    ),
    note=(
        "Elk deel omvat zijn eigen reeks bladen, zegt voor welke klant het is en "
        "hoeveel exemplaren er nodig zijn, en bevat het gegevensbestand dat bij dat "
        "deel hoort en bij geen ander. Leessoftware toont één document; een drukkerij "
        "leest er drie."
    ),
    statement="Afschrift",
    customer="Klant",
    sheet="Blad",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="Verenigd Koninkrijk",
    columns=("Omschrijving", "Bedrag"),
    lines=(
        "Goederen geleverd in juli",
        "Vervoer, vier kratten",
        "Opslag, één maand",
    ),
    total="Totaal",
    terms_title="Betalingsvoorwaarden",
    terms=(
        "Betaling vervalt dertig dagen na de verzenddatum van dit afschrift. Over een "
        "bedrag dat daarna nog openstaat, is driemaal de wettelijke rente "
        "verschuldigd, plus een vast bedrag van veertig euro voor de "
        "invorderingskosten. Betalingen worden gedaan op de rekening die op het "
        "afschrift staat, onder vermelding van het klantnummer."
    ),
    carried="Het afschrift als gegevensbestand",
)

# The pages in Portuguese.
PORTUGUESE = Words(
    title="Três extratos, um ficheiro",
    lead=(
        "As quatro folhas abaixo são três extratos, não um. Nada do que nelas está "
        "desenhado diz onde acaba um destinatário e começa o seguinte: di-lo o "
        "ficheiro, ao lado das páginas e não nelas, por isso uma gráfica pode "
        "imprimir e cortar esta tiragem sem um segundo ficheiro que a explique."
    ),
    note=(
        "Cada parte reclama a sua série de folhas, diz a que cliente se destina e "
        "quantas cópias lhe são devidas, e leva o ficheiro de dados que lhe pertence "
        "a ela e a mais nenhuma. Um programa de leitura mostra um documento; uma "
        "gráfica lê três."
    ),
    statement="Extrato",
    customer="Cliente",
    sheet="Folha",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="Reino Unido",
    columns=("Descrição", "Montante"),
    lines=(
        "Mercadoria entregue em julho",
        "Transporte, quatro caixas",
        "Armazenagem, um mês",
    ),
    total="Total",
    terms_title="Condições de pagamento",
    terms=(
        "O pagamento vence trinta dias após a data de envio deste extrato. Um "
        "montante ainda em dívida depois dessa data vence juros ao triplo da taxa "
        "legal, mais uma quantia fixa de quarenta euros pelos custos de cobrança. O "
        "pagamento faz-se para a conta indicada no extrato, citando o número de "
        "cliente."
    ),
    carried="O extrato como ficheiro de dados",
)

# The pages in Italian.
ITALIAN = Words(
    title="Tre estratti, un file",
    lead=(
        "I quattro fogli qui sotto sono tre estratti, non uno. Niente di disegnato su "
        "di essi dice dove finisce un destinatario e comincia il successivo: lo dice "
        "il file, accanto alle pagine e non sopra, così una tipografia può stampare e "
        "tagliare questa tiratura senza un secondo file che la spieghi."
    ),
    note=(
        "Ogni parte rivendica la propria serie di fogli, dice a quale cliente è "
        "destinata e quante copie gli spettano, e porta il file di dati che "
        "appartiene a lei e a nessun’altra. Un programma di lettura mostra un "
        "documento; una tipografia ne legge tre."
    ),
    statement="Estratto",
    customer="Cliente",
    sheet="Foglio",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="Regno Unito",
    columns=("Descrizione", "Importo"),
    lines=(
        "Merce consegnata a luglio",
        "Trasporto, quattro casse",
        "Deposito, un mese",
    ),
    total="Totale",
    terms_title="Condizioni di pagamento",
    terms=(
        "Il pagamento scade trenta giorni dopo la data di invio di questo estratto. "
        "Un importo ancora dovuto dopo tale data produce interessi al triplo del "
        "tasso legale, più una somma fissa di quaranta euro per le spese di recupero. "
        "Il pagamento si fa sul conto indicato nell’estratto, citando il numero "
        "cliente."
    ),
    carried="L’estratto come file di dati",
)

# The pages in Spanish.
SPANISH = Words(
    title="Tres extractos, un archivo",
    lead=(
        "Las cuatro hojas de abajo son tres extractos, no uno. Nada de lo dibujado en "
        "ellas dice dónde acaba un destinatario y empieza el siguiente: lo dice el "
        "archivo, junto a las páginas y no en ellas, así que una imprenta puede "
        "imprimir y cortar esta tirada sin un segundo archivo que la explique."
    ),
    note=(
        "Cada parte reclama su propia serie de hojas, dice a qué cliente va y cuántas "
        "copias se le deben, y lleva el archivo de datos que le pertenece a ella y a "
        "ninguna otra. Un programa de lectura muestra un documento; una imprenta lee "
        "tres."
    ),
    statement="Extracto",
    customer="Cliente",
    sheet="Hoja",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="Reino Unido",
    columns=("Descripción", "Importe"),
    lines=(
        "Mercancía entregada en julio",
        "Porte, cuatro cajas",
        "Almacenaje, un mes",
    ),
    total="Total",
    terms_title="Condiciones de pago",
    terms=(
        "El pago vence treinta días después de la fecha de envío de este extracto. Un "
        "importe aún debido tras esa fecha devenga intereses al triple del tipo "
        "legal, más una suma fija de cuarenta euros por los gastos de cobro. El pago "
        "se hace a la cuenta indicada en el extracto, citando el número de cliente."
    ),
    carried="El extracto como archivo de datos",
)

# The pages in German.
GERMAN = Words(
    title="Drei Kontoauszüge, eine Datei",
    lead=(
        "Die vier Blätter unten sind drei Kontoauszüge, nicht einer. Nichts darauf "
        "Gezeichnetes sagt, wo ein Empfänger endet und der nächste beginnt — das sagt "
        "die Datei, neben den Seiten statt auf ihnen, sodass eine Druckmaschine "
        "diesen Lauf drucken und schneiden kann, ohne dass eine zweite Datei ihn "
        "erklärt."
    ),
    note=(
        "Jeder Teil beansprucht seine eigene Blattfolge, nennt den Kunden, für den er "
        "bestimmt ist, und die Zahl der zu liefernden Exemplare, und trägt die "
        "Datendatei, die zu ihm und zu keinem anderen Teil gehört. Eine Lesesoftware "
        "zeigt ein Dokument; eine Druckmaschine liest drei."
    ),
    statement="Kontoauszug",
    customer="Kunde",
    sheet="Blatt",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="Vereinigtes Königreich",
    columns=("Beschreibung", "Betrag"),
    lines=(
        "Im Juli gelieferte Waren",
        "Fracht, vier Kisten",
        "Lagerung, ein Monat",
    ),
    total="Summe",
    terms_title="Zahlungsbedingungen",
    terms=(
        "Die Zahlung ist dreißig Tage nach dem Versanddatum dieses Kontoauszugs "
        "fällig. Ein danach noch offener Betrag wird mit dem Dreifachen des "
        "gesetzlichen Zinssatzes verzinst, zuzüglich einer Pauschale von vierzig Euro "
        "für die Kosten der Beitreibung. Die Zahlung erfolgt auf das auf dem "
        "Kontoauszug genannte Konto unter Angabe der Kundennummer."
    ),
    carried="Der Kontoauszug als Datendatei",
)

# 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}

# The left edge of everything on the pages.
LEFT = 72.0

# How wide a block of text, and a statement, are.
WIDTH = 451.0

# The space that keeps an amount's thousands from being read as a new number.
NO_BREAK = " "

# The number each customer is known by.
NUMBERS = ("4711", "4712", "4713")

# How many copies of each statement the run owes.
COPIES = (2, 1, 3)

# What each statement's envelope weighs, in kilograms.
WEIGHTS = [0.12, 0.08, 0.16]

# When each statement was posted.
POSTED = (
    "2026-08-03T09:15:00+02:00",
    "2026-08-03T09:16:00+02:00",
    "2026-08-03T09:17:00+02:00",
)

# What each statement charges, line by line, in cents.
AMOUNTS = (
    (125_000, 9_600, 21_025),
    (48_050, 4_800, 21_025),
    (312_400, 15_200, 42_050),
)

# The sheets each statement claims: the first, and the one after the last. The first
# statement runs to two sheets, its terms following it; the other two are a sheet each.
RUNS = ((0, 2), (2, 3), (3, 4))


def money(cents: int) -> str:
    """An amount of cents, its thousands parted by a no-break space and its decimals
    by a point, which is how every language this example is written in writes one."""
    whole, fraction = divmod(cents, 100)
    digits = str(whole)
    out = []
    for index, digit in enumerate(digits):
        if index > 0 and (len(digits) - index) % 3 == 0:
            out.append(NO_BREAK)
        out.append(digit)
    return f"{''.join(out)}.{fraction:02d}{NO_BREAK}EUR"


def block(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    size: float,
    top: float,
    text: str,
) -> float:
    """Sets a block of words at `top`, and hands back the ordinate it ends at."""
    flow = hqf_pdf.TextFlow(handle, size)
    lines = flow.break_lines(text, WIDTH)
    # The binding opens the text object itself, so opening another here would write a
    # pair of operators its twin in Rust does not.
    flow.draw(content, lines, LEFT, top, WIDTH)
    return top - flow.height(lines)


def charges(words: Words, text: hqf_pdf.FontHandle, index: int) -> hqf_pdf.Table:
    """The lines and total of one statement."""
    columns = hqf_pdf.Columns(
        [hqf_pdf.ColumnWidth.fraction(1.0), hqf_pdf.ColumnWidth.points(110.0)],
        WIDTH,
    )

    table = hqf_pdf.Table(columns)
    table.header(1)
    hairline = hqf_pdf.Stroke(0.5, color=hqf_pdf.Rgb.gray(0.6))
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.75))
    table.rule(hqf_pdf.Rule.horizontal_other(), hairline)
    table.rule(hqf_pdf.Rule.vertical(1), hairline)

    pad = hqf_pdf.Padding.symmetric(5.0, 4.0)
    shade = hqf_pdf.Rgb(0.93, 0.94, 0.97)
    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(text, 9.5, words.columns[0], padding=pad, fill=shade),
                hqf_pdf.Cell(
                    text,
                    9.5,
                    words.columns[1],
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                    fill=shade,
                ),
            ],
            min_height=19.0,
        )
    )

    for label, amount in zip(words.lines, AMOUNTS[index]):
        table.push(
            hqf_pdf.Row(
                cells=[
                    hqf_pdf.Cell(text, 9.0, label, padding=pad),
                    hqf_pdf.Cell(
                        text,
                        9.0,
                        money(amount),
                        padding=pad,
                        align=hqf_pdf.Align.Right,
                    ),
                ],
                min_height=16.0,
            )
        )

    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(text, 9.5, words.total, padding=pad),
                hqf_pdf.Cell(
                    text,
                    9.5,
                    money(sum(AMOUNTS[index])),
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                ),
            ],
            min_height=19.0,
        )
    )
    return table


def foot(
    content: hqf_pdf.Content,
    words: Words,
    text: hqf_pdf.FontHandle,
    index: int,
    sheet: int,
) -> None:
    """Draws the foot of a sheet: who it is for, and where it stands in its
    statement."""
    first, after = RUNS[index]
    flow = hqf_pdf.TextFlow(text, 8.0)
    line = (
        f"{words.statement} {index + 1}/{len(RUNS)} — {words.recipients[index]}"
        f" — {words.sheet} {sheet + 1}/{after - first}"
    )
    content.set_fill(hqf_pdf.Rgb.gray(0.45))
    flow.draw(content, flow.break_lines(line, WIDTH), LEFT, 56.0, WIDTH)
    content.set_fill(hqf_pdf.Rgb.gray(0.0))


def charge_sheet(words: Words, text: hqf_pdf.FontHandle, index: int) -> hqf_pdf.Content:
    """Draws the sheet a statement is charged on."""
    content = hqf_pdf.Content()
    top = 782.0

    if index == 0:
        top = block(content, text, 17.0, top, words.title) - 12.0
        top = block(content, text, 9.5, top, words.lead) - 26.0

    top = block(content, text, 13.0, top, words.recipients[index]) - 6.0
    whereabouts = (
        f"{words.customer} {NUMBERS[index]} —"
        f" {words.towns[index]}, {words.country}"
    )
    top = block(content, text, 9.0, top, whereabouts) - 20.0

    placed = charges(words, text, index).fit(LEFT, top, 120.0)
    placed.draw(content)

    if index == 0:
        content.set_fill(hqf_pdf.Rgb.gray(0.35))
        block(content, text, 8.5, placed.bottom - 26.0, words.note)
        content.set_fill(hqf_pdf.Rgb.gray(0.0))

    foot(content, words, text, index, 0)
    return content


def terms_sheet(words: Words, text: hqf_pdf.FontHandle) -> hqf_pdf.Content:
    """Draws the terms sheet that follows the first statement."""
    content = hqf_pdf.Content()
    top = block(content, text, 13.0, 782.0, words.terms_title) - 14.0
    block(content, text, 9.5, top, words.terms)
    foot(content, words, text, 0, 1)
    return content


def carried(words: Words, index: int) -> hqf_pdf.Attachment:
    """The data file carried beside one statement."""
    total = sum(AMOUNTS[index])
    return hqf_pdf.Attachment(
        f"statement-{NUMBERS[index]}.xml",
        words.carried,
        "text/xml",
        hqf_pdf.Relationship.Data,
        POSTED[index],
        f'<statement customer="{NUMBERS[index]}" total="{total}"/>\n'.encode(),
    )


def stated(words: Words, index: int) -> hqf_pdf.PartData:
    """What one statement states about itself, for whatever prints it: text, a whole
    number, a real one, a date, a yes or no, a list and a set of fields of its own.

    A proof flag steers the preview while the part is put together and is not for the
    press: it is taken out again before the part is written.
    """
    address = hqf_pdf.PartData(
        entries=[("Town", words.towns[index]), ("Country", words.country)]
    )
    data = hqf_pdf.PartData(
        entries=[
            ("Recipient", words.recipients[index]),
            ("CustomerNumber", NUMBERS[index]),
            ("Copies", COPIES[index]),
            ("Posted", hqf_pdf.PartValue.date(POSTED[index])),
            ("Address", address),
            ("Weight", WEIGHTS[index]),
            ("Tracked", index == 0),
            ("Enclosures", [f"statement-{NUMBERS[index]}.xml"]),
            ("Proof", True),
        ]
    )
    data.unset("Proof")
    return data


def copies_stated(words: Words) -> tuple[int, int]:
    """How many copies every statement stated comes to, read back from what each
    states, and how many statements state anything at all."""
    copies = 0
    stating = 0
    for index in range(len(RUNS)):
        data = stated(words, index)
        if not data.is_empty():
            stating += 1
        value = data.get("Copies")
        if value is not None:
            copies += value.value
    return copies, stating


def hierarchy(
    words: Words, files: list[hqf_pdf.AttachmentHandle]
) -> hqf_pdf.DocumentParts:
    """The hierarchy: one part per statement, under the part that is the whole run."""
    statements = [
        hqf_pdf.DocumentPart(
            pages=RUNS[index],
            data=stated(words, index),
            associated_files=[file],
        )
        for index, file in enumerate(files)
    ]
    return hqf_pdf.DocumentParts(
        hqf_pdf.DocumentPart(children=statements),
        node_names=["Run", "Statement"],
        record_level=1,
    )


def to_statement(index: int) -> hqf_pdf.Link:
    """The foot of a sheet of statement `index`, as a link leading to the part that
    claims the statement's first sheet."""
    first, __ = RUNS[index]
    return hqf_pdf.Link.acting(LEFT, 52.0, WIDTH, 12.0, hqf_pdf.Action.to_part(first))


def build(words: Words, font: Path) -> bytes:
    """Draws the four sheets and says which of them belong to which statement."""
    doc = hqf_pdf.Document()
    doc.set_license(_licence.licensed())
    # The hierarchy of document parts is written on PDF 2.0 and on nothing earlier.
    doc.set_version(hqf_pdf.Version.V2_0)
    text = doc.add_font(hqf_pdf.Font.from_path(font))

    files = [doc.attach(carried(words, index)) for index in range(len(RUNS))]

    first = hqf_pdf.Page.a4()
    first.set_content(charge_sheet(words, text, 0))
    first.add_link(to_statement(0))
    doc.add_page(first)

    second = hqf_pdf.Page.a4()
    second.set_content(terms_sheet(words, text))
    second.add_link(to_statement(0))
    doc.add_page(second)

    for index in range(1, len(RUNS)):
        sheet = hqf_pdf.Page.a4()
        sheet.set_content(charge_sheet(words, text, index))
        sheet.add_link(to_statement(index))
        doc.add_page(sheet)

    doc.set_document_parts(hierarchy(words, files))
    return doc.to_bytes()


def main() -> None:
    """Writes the four sheets."""
    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("document_parts.pdf", language)).stem
    )

    data = build(words, _out.font_path())

    Path(out).parent.mkdir(parents=True, exist_ok=True)
    Path(out).write_bytes(data)
    copies, stating = copies_stated(words)
    print(
        f"wrote {out}: {len(data)} bytes, {stating} statements asking for "
        f"{copies} copies"
    )


if __name__ == "__main__":
    main()
