"""Hands a long table over whole, and lets it decide how many pages it needs.

The Python twin of the `write_table_paginated` example in Rust, and the shape a
document server wants: build the table, say what box it gets on the first page and
what box it gets on the ones after, and call `paginate` once. It answers with one
placement per page. The caller makes each page — here, by stamping it onto an
imported stationery template — and draws the placement onto it. No loop to write,
and no way to write it wrong: a table that could not advance raises, rather than
asking for another blank page.

Five things the table does on its own:

  - the caption is set over the table on every page, its room taken off the box
    before a row is placed;
  - the heading row is drawn again at the top of every page;
  - the footnote row is drawn again under the last line of every page;
  - a section title is kept with the rows under it, so it is never stranded at the
    foot of a page away from what it introduces;
  - the cell naming a quarter covers every row of that quarter, and where a page
    ends inside the quarter it is cut there and drawn again at the top of the next
    page, over the rows left.

Under each page the caller adds a note of its own, saying which of the table's rows
the page carried and hanging its page number on the grid line before the
amounts. The placement is asked for all of it: where its rows ended, where that grid
line fell, and which rows it took.

Every word the statement draws is held in `Words`, once per language, and
`HQF_PDF_LANG` picks which one is drawn. The amounts are the same in both.

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

from __future__ import annotations

import sys
from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

PAGE_WIDTH = 595.276
MARGIN = 56.0
TABLE_WIDTH = PAGE_WIDTH - 2 * MARGIN

# The table starts below the letterhead on the first page, and higher up on every page
# after it: that is the whole reason `paginate` takes two boxes.
FIRST_TOP = 700.0
NEXT_TOP = 800.0
BOTTOM = 64.0


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

    What is not language stays out of it: the amounts, the company's name and its
    address read the same in every language.
    """

    # The line the letterhead of the stationery carries.
    letterhead: str
    # The three column headings.
    period: str
    description: str
    amount: str
    # What the cell heading each quarter's rows says; ``{n}`` stands for its number.
    quarter: str
    # What each section is called, in the order ``SECTIONS`` gives them.
    sections: tuple[str, ...]
    # What each billed line is called, section after section.
    lines: tuple[str, ...]
    # The label of the boxed total.
    total: str
    # The footnote repeated under the last line of every page.
    footnote: str
    # The caption set over the table on every page.
    caption: str
    # The caller's own note, cut where the row numbers go into it.
    rows_before: str
    rows_between: str
    rows_of: str
    # The same for the page number.
    page_before: str
    page_of: str


# The statement in English.
ENGLISH = Words(
    letterhead="ACME Ltd — statement of services",
    period="Quarter",
    quarter="Q{n}",
    description="Description",
    amount="Amount",
    sections=(
        "Development",
        "Reworking what was there",
        "Support",
        "Audit",
    ),
    lines=(
        "Rendering engine",
        "Font engine",
        "Glyph subsetting",
        "Charstring interpreter",
        "Tables and layout",
        "Invoice template",
        "Data migration",
        "Acceptance testing and fixes",
        "Team training",
        "Standby cover for the release night",
        "First year of support",
        "Technical documentation",
        "Performance audit",
        "Security audit",
        "Architecture review",
    ),
    total="Total due",
    footnote=(
        "Amounts in euros, exclusive of value added tax. ACME Ltd, "
        "Bureau 4, 12 rue des Fabriques, 59000 Lille."
    ),
    caption="Statement of services for the year, carried on from page to page",
    rows_before="Rows ",
    rows_between=" to ",
    rows_of=" of ",
    page_before="Page ",
    page_of=" of ",
)

# The statement in French.
FRENCH = Words(
    letterhead="ACME Ltd — relevé de prestations",
    period="Trimestre",
    quarter="T{n}",
    description="Désignation",
    amount="Montant",
    sections=(
        "Développement",
        "Reprise de l’existant",
        "Assistance",
        "Audit",
    ),
    lines=(
        "Moteur de rendu",
        "Moteur de polices",
        "Réduction des polices aux glyphes utilisés",
        "Interpréteur de contours de glyphes",
        "Tableaux et mise en page",
        "Modèle de facture",
        "Migration des données",
        "Recette et corrections",
        "Formation de l’équipe",
        "Astreinte la nuit de la mise en production",
        "Première année d’assistance",
        "Documentation technique",
        "Audit de performance",
        "Audit de sécurité",
        "Revue d’architecture",
    ),
    total="Total dû",
    footnote=(
        ("Montants en euros, hors TVA. ACME Ltd, Bureau 4, 12 rue des Fabriques, 59000"
         " Lille.")
    ),
    caption="Relevé des prestations de l’année, poursuivi de page en page",
    rows_before="Lignes ",
    rows_between=" à ",
    rows_of=" sur ",
    page_before="Page ",
    page_of=" sur ",
)

# The statement in Dutch.
DUTCH = Words(
    letterhead="ACME Ltd — overzicht van diensten",
    period="Kwartaal",
    quarter="K{n}",
    description="Omschrijving",
    amount="Bedrag",
    sections=(
        "Ontwikkeling",
        "Bestaand werk herzien",
        "Ondersteuning",
        "Audit",
    ),
    lines=(
        "Opmaakmotor",
        "Lettertypemotor",
        "Glyph-subsetting",
        "Charstring-interpreter",
        "Tabellen en opmaak",
        "Factuursjabloon",
        "Gegevensmigratie",
        "Acceptatietests en correcties",
        "Teamtraining",
        "Stand-by voor de lanceringsnacht",
        "Eerste jaar ondersteuning",
        "Technische documentatie",
        "Prestatieaudit",
        "Beveiligingsaudit",
        "Architectuurreview",
    ),
    total="Te betalen",
    footnote=(
        "Bedragen in euro, exclusief btw. ACME Ltd, Bureau 4, 12 rue des Fabriques, "
        "59000 Lille."
    ),
    caption="Overzicht van diensten over het jaar, doorgezet van pagina tot pagina",
    rows_before="Rijen",
    rows_between=" tot",
    rows_of=" van",
    page_before="Pagina",
    page_of=" van",
)

# The statement in Portuguese.
PORTUGUESE = Words(
    letterhead="ACME Ltd — relação de serviços",
    period="Trimestre",
    quarter="{n}.º trim.",
    description="Descrição",
    amount="Montante",
    sections=(
        "Desenvolvimento",
        "Refazer o que existia",
        "Suporte",
        "Auditoria",
    ),
    lines=(
        "Motor de paginação",
        "Motor de tipos de letra",
        "Subconjunto de glifos",
        "Intérprete de charstrings",
        "Tabelas e paginação",
        "Modelo de fatura",
        "Migração de dados",
        "Testes de aceitação e correções",
        "Formação da equipa",
        "Prevenção para a noite do lançamento",
        "Primeiro ano de suporte",
        "Documentação técnica",
        "Auditoria de desempenho",
        "Auditoria de segurança",
        "Revisão de arquitetura",
    ),
    total="Total a pagar",
    footnote=(
        "Montantes em euros, sem imposto sobre o valor acrescentado. ACME Ltd, Bureau "
        "4, 12 rue des Fabriques, 59000 Lille."
    ),
    caption="Relação de serviços do ano, transportada de página em página",
    rows_before="Linhas",
    rows_between=" a",
    rows_of=" de",
    page_before="Página",
    page_of=" de",
)

# The statement in Italian.
ITALIAN = Words(
    letterhead="ACME Ltd — prospetto dei servizi",
    period="Trimestre",
    quarter="{n}º trim.",
    description="Descrizione",
    amount="Importo",
    sections=(
        "Sviluppo",
        "Rifacimento dell’esistente",
        "Assistenza",
        "Verifica",
    ),
    lines=(
        "Motore di impaginazione",
        "Motore dei font",
        "Sottoinsieme dei glifi",
        "Interprete di charstring",
        "Tabelle e impaginazione",
        "Modello di fattura",
        "Migrazione dei dati",
        "Collaudo e correzioni",
        "Formazione del team",
        "Reperibilità per la notte del rilascio",
        "Primo anno di assistenza",
        "Documentazione tecnica",
        "Verifica delle prestazioni",
        "Verifica di sicurezza",
        "Revisione dell’architettura",
    ),
    total="Totale dovuto",
    footnote=(
        "Importi in euro, al netto dell’imposta sul valore aggiunto. ACME Ltd, Bureau "
        "4, 12 rue des Fabriques, 59000 Lille."
    ),
    caption="Prospetto dei servizi dell’anno, riportato di pagina in pagina",
    rows_before="Righe",
    rows_between=" –",
    rows_of=" di",
    page_before="Pagina",
    page_of=" di",
)

# The statement in Spanish.
SPANISH = Words(
    letterhead="ACME Ltd — relación de servicios",
    period="Trimestre",
    quarter="{n}T",
    description="Descripción",
    amount="Importe",
    sections=(
        "Desarrollo",
        "Rehacer lo existente",
        "Soporte",
        "Auditoría",
    ),
    lines=(
        "Motor de maquetación",
        "Motor de fuentes",
        "Subconjunto de glifos",
        "Intérprete de charstrings",
        "Tablas y maquetación",
        "Plantilla de factura",
        "Migración de datos",
        "Pruebas de aceptación y correcciones",
        "Formación del equipo",
        "Guardia para la noche del lanzamiento",
        "Primer año de soporte",
        "Documentación técnica",
        "Auditoría de rendimiento",
        "Auditoría de seguridad",
        "Revisión de arquitectura",
    ),
    total="Total a pagar",
    footnote=(
        "Importes en euros, sin impuesto sobre el valor añadido. ACME Ltd, Bureau 4, "
        "12 rue des Fabriques, 59000 Lille."
    ),
    caption="Relación de servicios del año, continuada de página en página",
    rows_before="Filas",
    rows_between=" a",
    rows_of=" de",
    page_before="Página",
    page_of=" de",
)

# The statement in German.
GERMAN = Words(
    letterhead="ACME Ltd — Leistungsaufstellung",
    period="Quartal",
    quarter="Q{n}",
    description="Beschreibung",
    amount="Betrag",
    sections=(
        "Entwicklung",
        "Überarbeitung des Bestehenden",
        "Support",
        "Prüfung",
    ),
    lines=(
        "Rendering-Engine",
        "Font-Engine",
        "Glyphen-Teilmengen",
        "Charstring-Interpreter",
        "Tabellen und Layout",
        "Rechnungsvorlage",
        "Datenmigration",
        "Abnahmetests und Korrekturen",
        "Schulung des Teams",
        "Bereitschaft in der Nacht der Auslieferung",
        "Erstes Jahr Support",
        "Technische Dokumentation",
        "Leistungsprüfung",
        "Sicherheitsprüfung",
        "Architekturprüfung",
    ),
    total="Zu zahlen",
    footnote=(
        "Beträge in Euro, zuzüglich Mehrwertsteuer. ACME Ltd, Bureau 4, 12 rue des "
        "Fabriques, 59000 Lille."
    ),
    caption="Leistungsaufstellung für das Jahr, von Seite zu Seite fortgeführt",
    rows_before="Zeilen ",
    rows_between=" bis ",
    rows_of=" von ",
    page_before="Seite ",
    page_of=" von ",
)


# 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 a_stationery(font_path, words: Words) -> bytes:
    """The stationery every page is stamped onto, for when the caller has none."""
    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(font_path))

    content = hqf_pdf.Content()
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.91, 0.94, 0.98))
    content.rect(0.0, 812.0, PAGE_WIDTH, 30.0)
    content.fill()
    content.set_fill(hqf_pdf.Rgb(0.2, 0.35, 0.6))
    content.rect(0.0, 809.0, PAGE_WIDTH, 3.0)
    content.fill()
    content.restore_state()

    content.draw_text(font, 13.0, MARGIN, 820.0, words.letterhead)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)
    return document.to_bytes()


@dataclass(frozen=True)
class Section:
    """One section of the statement: what each of its lines is billed, in the order
    ``Words.lines`` names them."""

    lines: tuple[float, ...]


SECTIONS = (
    Section((7440.0, 4960.0, 2480.0, 3720.0, 5580.0)),
    Section((1440.0, 2700.0, 2880.0)),
    Section((1500.0, 1200.0, 4200.0, 1260.0)),
    Section((2760.0, 3100.0, 1850.0)),
)


def amount(value: float) -> str:
    """An amount, as a statement writes it: "4 250.00 EUR"."""
    units, hundredths = f"{value:.2f}".split(".")
    grouped = ""
    for index, digit in enumerate(units):
        if index > 0 and (len(units) - index) % 3 == 0:
            grouped += " "
        grouped += digit
    return f"{grouped}.{hundredths} EUR"


def statement(font: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Table:
    """The statement, as one table: a heading, then every section, four times over
    so that it runs well past a single page."""
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.points(64.0),
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(110.0),
        ],
        TABLE_WIDTH,
    )

    table = hqf_pdf.Table(columns)
    # A quarter's rows that a page cannot hold whole are cut between two of them, rather
    # than all moved to the next page.
    table.split_rows(True)
    # The heading row is drawn again at the top of every page, and the footnote row
    # under the last line of every page.
    table.header(1)
    table.footer(1)
    table.caption_above(hqf_pdf.TextFlow(font, 10.0), words.caption, gap=6.0)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8))
    table.rule(
        hqf_pdf.Rule.horizontal_other(),
        hqf_pdf.Stroke(0.25, color=hqf_pdf.Rgb.gray(0.75)),
    )
    table.rule(hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.8))
    table.rule(
        hqf_pdf.Rule.vertical(1), hqf_pdf.Stroke(0.25, color=hqf_pdf.Rgb.gray(0.75))
    )
    # The shading is said once, for the table, rather than cell by cell: every other row
    # faintly, and the heading over the top of that.
    table.fill(hqf_pdf.Area.even_rows(), hqf_pdf.Rgb.gray(0.97))
    table.fill(hqf_pdf.Area.header(), hqf_pdf.Rgb.gray(0.88))

    pad = hqf_pdf.Padding.symmetric(5.0, 4.0)

    def heading(label: str, align: hqf_pdf.Align) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            9.0,
            label,
            padding=pad,
            align=align,
            valign=hqf_pdf.VAlign.Middle,
        )

    table.push(
        hqf_pdf.Row(
            cells=[
                heading(words.period, hqf_pdf.Align.Left),
                heading(words.description, hqf_pdf.Align.Left),
                heading(words.amount, hqf_pdf.Align.Right),
            ],
            min_height=20.0,
        )
    )

    # Every quarter covers each section's title and each of its lines.
    quarter_rows = sum(1 + len(section.lines) for section in SECTIONS)
    for round_ in range(4):
        line = 0
        for index, (section, title) in enumerate(zip(SECTIONS, words.sections)):
            # The cell naming the quarter begins on its first row and covers all of
            # them, drawn again at the top of a page that takes them up.
            first = []
            if index == 0:
                first.append(
                    hqf_pdf.Cell(
                        font,
                        9.5,
                        words.quarter.replace("{n}", str(round_ + 1)),
                        padding=pad,
                        span_rows=quarter_rows,
                        repeated_when_cut=True,
                    )
                )
            # The section title is kept with the first line under it: a title alone at
            # the foot of a page introduces nothing.
            table.push(
                hqf_pdf.Row(
                    cells=[
                        *first,
                        hqf_pdf.Cell(
                            font,
                            9.5,
                            f"{title} ({round_ + 1})",
                            padding=pad,
                            span=2,
                            fill=hqf_pdf.Rgb.gray(0.93),
                            border=hqf_pdf.Border(bottom=hqf_pdf.Stroke(0.5)),
                        )
                    ],
                    min_height=18.0,
                    keep_with_next=True,
                )
            )

            for value in section.lines:
                label = words.lines[line]
                line += 1
                table.push(
                    hqf_pdf.Row(
                        cells=[
                            hqf_pdf.Cell(font, 9.0, label, padding=pad),
                            hqf_pdf.Cell(
                                font,
                                9.0,
                                amount(value),
                                padding=pad,
                                align=hqf_pdf.Align.Right,
                            ),
                        ],
                        min_height=16.0,
                    )
                )

    # The total, boxed, and kept with nothing: it ends the table.
    total = sum(value for s in SECTIONS for value in s.lines) * 4
    rule = hqf_pdf.Stroke(0.8)
    box_margin = hqf_pdf.Margin.symmetric(0.0, 2.0)
    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(
                    font,
                    10.0,
                    words.total,
                    padding=pad,
                    span=2,
                    align=hqf_pdf.Align.Right,
                    margin=box_margin,
                    border=hqf_pdf.Border(top=rule, bottom=rule, left=rule),
                ),
                hqf_pdf.Cell(
                    font,
                    10.0,
                    amount(total),
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                    margin=box_margin,
                    border=hqf_pdf.Border(top=rule, bottom=rule, right=rule),
                ),
            ],
            min_height=20.0,
        )
    )

    # The footnote, repeated under the last line of every page.
    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(
                    font,
                    7.5,
                    words.footnote,
                    padding=pad,
                    span=3,
                    color=hqf_pdf.Rgb.gray(0.45),
                ),
            ],
            space_before=6.0,
        )
    )

    return table


def continuation_note(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    words: Words,
    placed: hqf_pdf.FittedTable,
    page: int,
    pages: int,
    rows: int,
) -> None:
    """Draws the caller's own note under a page's table.

    Everything it needs comes from the placement: where the rows ended, where the
    table's left edge and the grid line before the amounts fell, and which of
    the table's rows this page carried. Nothing here counts rows or adds heights on
    the side, so the note cannot drift away from the table it describes.
    """
    body = placed.body_rows
    if body is None:
        return
    baseline = placed.bottom - 12.0

    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.45, 0.45, 0.45))
    content.draw_text(
        font,
        7.5,
        placed.x,
        baseline,
        f"{words.rows_before}{body.start}{words.rows_between}"
        f"{body.stop - 1}{words.rows_of}{rows}",
    )

    content.draw_text(
        font,
        7.5,
        placed.column_x(2),
        baseline,
        f"{words.page_before}{page + 1}{words.page_of}{pages}",
    )

    content.restore_state()


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("paginated.pdf", language)).stem)
    font_path = _out.DEFAULT_FONT

    # The stationery every page is stamped onto: the caller's, or one made here.
    if len(sys.argv) > 2:
        stationery = open(sys.argv[2], "rb").read()
    else:
        stationery = a_stationery(font_path, words)
    reader = hqf_pdf.Reader(stationery)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    template = document.import_page(reader, 0)
    font = document.add_font(hqf_pdf.Font.from_path(font_path))

    table = statement(font, words)

    # The whole of pagination: one call, one placement per page.
    pages = table.paginate(
        hqf_pdf.TableFrame(MARGIN, FIRST_TOP, FIRST_TOP - BOTTOM),
        hqf_pdf.TableFrame(MARGIN, NEXT_TOP, NEXT_TOP - BOTTOM),
    )

    for index, placed in enumerate(pages):
        content = hqf_pdf.Content()
        # The stationery goes down first, and the table on top of it.
        content.draw_form(template, 0.0, 0.0, 1.0)
        placed.draw(content)
        continuation_note(
            content, font, words, placed, index, len(pages), table.row_count
        )

        page = hqf_pdf.Page.a4()
        page.set_content(content)
        # The stationery is a form, and a page may only draw what its resources name.
        template.add_to(page)
        document.add_page(page)

    written = document.write(out)
    print(f"wrote {out}: {written} bytes, {len(pages)} pages, {table.row_count} rows")


if __name__ == "__main__":
    main()
