"""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.

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. A reader 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 sont trois relevés, et non un seul. Rien de "
        "ce qui est dessiné dessus ne dit où finit un destinataire et où commence le "
        "suivant : c'est le fichier qui le dit, à côté des pages plutôt que dessus, "
        "de sorte qu'un imprimeur tire et coupe ce lot sans un second fichier pour le "
        "lui expliquer."
    ),
    note=(
        "Chaque partie revendique sa propre suite de feuillets, énonce le client à "
        "qui elle s'adresse et le nombre d'exemplaires dus, et emporte le fichier de "
        "données qui lui appartient et qui n'appartient à aucune autre. Un lecteur "
        "montre 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 porte intérêt au triple du "
        "taux légal, augmenté d'une indemnité forfaitaire de quarante euros pour "
        "frais de recouvrement. Le règlement est fait sur le compte indiqué au "
        "relevé, sous le numéro de client."
    ),
    carried="Le relevé sous forme de fichier de données",
)

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

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

# 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, 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(
            [
                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(
                [
                    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(
            [
                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."""
    address = hqf_pdf.PartData(
        [("Town", words.towns[index]), ("Country", words.country)]
    )
    return hqf_pdf.PartData(
        [
            ("Recipient", words.recipients[index]),
            ("CustomerNumber", NUMBERS[index]),
            ("Copies", COPIES[index]),
            ("Posted", hqf_pdf.PartValue.date(POSTED[index])),
            ("Address", address),
        ]
    )


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 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))
    doc.add_page(first)

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

    for index in range(1, len(RUNS)):
        sheet = hqf_pdf.Page.a4()
        sheet.set_content(charge_sheet(words, text, 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)
    print(f"wrote {out}: {len(data)} bytes")


if __name__ == "__main__":
    main()
