"""Writes a schedule of charges claiming the third part of the archival
standard, at level A, carrying the same table in the form a machine reads.

The third part is the one that lets a record carry a file of any kind, and
level A is the one that asks the page to say what it is made of. Together
they make a record a screen reader can follow and a billing system can read
without anybody retyping it.

The rule and the page number at the foot are marked as furniture, so
nothing reading the document aloud says them.

Whether the result really is PDF/A-3A is not for us to say. `veraPDF` says,
and `scripts/check_archival.sh` asks it.

The words of the page and of its metadata are held in `Words`, once per language,
and `HQF_PDF_LANG` picks which set the record is written in. The tree names the same
language, so a screen reader reads the page in it.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# When the record was drawn up. The library never reads the clock, so the caller says
# when.
ISSUED = "2026-06-08T09:20:00+02:00"

# Who the file says wrote it, and what produced it, in every language alike.
AUTHOR = "HQF Development"
PRODUCER = "hqf-pdf-server"

# The file the record carries. What it is to the record is said in `Words`.
CARRIED_NAME = "schedule.csv"
CARRIED_TYPE = "text/csv"
CHANGED = "2026-06-08T09:15:00+02:00"
CARRIED = "charge,basis,amount\ncarriage,consignment,12.40\nhandling,parcel,1.85\nstorage,day,0.40\n"

@dataclass(frozen=True)
class Words:
    """Every word the schedule is written in, in one language."""

    # What the file says it is, in its metadata.
    title: str
    # What the file says it is about, in its metadata.
    subject: str
    # The language the tree says the page is written in, which a screen reader reads it
    # in.
    lang: str
    # What the carried file says it is to the record.
    carried_what: str
    # The heading, tagged `H1`.
    heading: str
    # The two paragraphs under the heading, each tagged `P`.
    paragraphs: tuple[str, str]
    # The page number at the foot, marked as furniture.
    foot: str


# The schedule in English.
ENGLISH = Words(
    title="Schedule of charges, second half of 2026",
    subject="A record that says what it is made of and carries the table behind it",
    lang="en-GB",
    carried_what="The charges this page states, as a machine reads them",
    heading="Schedule of charges, second half of 2026",
    paragraphs=(
        (
            "This schedule claims the third part of the archival standard at its "
            "highest level. It may carry a file of any kind, and it says what it is "
            "made of: this line is a heading, the block below is a paragraph, and the "
            "rule across the foot is furniture that says nothing at all.\nSomething "
            "reading the schedule aloud follows the order the tree gives rather than "
            "the order the ink was laid down in, and the table behind the page travels "
            "inside the file for a program to take whole."
        ),
        (
            "Carriage stands at 12.40 the consignment, handling at 1.85 the parcel, "
            "and storage at 0.40 the day. A charge takes effect on the day the "
            "consignment is accepted."
        ),
    ),
    foot="Page 1 of 1",
)


# The schedule in French.
FRENCH = Words(
    title="Barème des frais, second semestre 2026",
    subject=(
        "Un document qui dit de quoi il est fait et contient le tableau dont il découle"
    ),
    lang="fr-FR",
    carried_what="Les frais que cette page indique, sous la forme que lit une machine",
    heading="Barème des frais, second semestre 2026",
    paragraphs=(
        (
            ("Ce barème déclare suivre la troisième partie de la norme d’archivage, à "
             "son niveau le plus exigeant. Il peut contenir un fichier de toute "
             "nature, et il dit de quoi il est fait : cette ligne est un titre, le "
             "bloc suivant est un paragraphe, et le filet en pied de page est un "
             "ornement qui ne dit rien.\nUn logiciel qui lit le barème à voix haute "
             "suit l’ordre que donne l’arbre de structure, et non celui dans lequel "
             "l’encre a été posée ; le tableau dont la page découle voyage dans le "
             "fichier, prêt à être repris tel quel par un programme.")
        ),
        (
            ("Le transport coûte 12,40 par envoi, la manutention 1,85 par colis et le "
             "stockage 0,40 par jour. Un tarif s’applique dès le jour où l’envoi est "
             "accepté.")
        ),
    ),
    foot="Page 1 sur 1",
)


# The schedule in German.
GERMAN = Words(
    title="Gebührenübersicht, zweites Halbjahr 2026",
    subject=(
        "Ein Dokument, das angibt, woraus es besteht, und die Tabelle dahinter enthält"
    ),
    lang="de-DE",
    carried_what="Die Gebühren dieser Seite, so wie eine Maschine sie liest",
    heading="Gebührenübersicht, zweites Halbjahr 2026",
    paragraphs=(
        (
            ("Diese Gebührenübersicht erklärt Konformität mit dem dritten Teil der "
             "Archivnorm, auf dessen höchster Stufe. Sie darf eine Datei beliebiger "
             "Art enthalten und gibt an, woraus sie besteht: Diese Zeile ist eine "
             "Überschrift, der Block darunter ein Absatz, und die Linie am Fuß ist "
             "Zierrat ohne jede Aussage.\nEin Vorleseprogramm folgt der Ordnung des "
             "Strukturbaums statt der Reihenfolge, in der die Tinte aufgetragen wurde,"
             " und die Tabelle hinter der Seite reist in der Datei mit, damit ein "
             "Programm sie vollständig übernehmen kann.")
        ),
        (
            ("Die Fracht kostet 12,40 je Sendung, der Umschlag 1,85 je Paket und die "
             "Lagerung 0,40 je Tag. Eine Gebühr fällt an dem Tag an, an dem die "
             "Sendung angenommen wird.")
        ),
    ),
    foot="Seite 1 von 1",
)


# The schedule in Spanish.
SPANISH = Words(
    title="Tarifa de gastos, segundo semestre de 2026",
    subject=(
        ("Un documento que dice de qué está hecho y contiene la tabla de la que "
         "proceden sus cifras")
    ),
    lang="es-ES",
    carried_what="Los gastos que indica esta página, tal como los lee una máquina",
    heading="Tarifa de gastos, segundo semestre de 2026",
    paragraphs=(
        (
            ("Esta tarifa declara cumplir la tercera parte de la norma de archivo en "
             "su nivel más alto. Puede llevar un fichero de cualquier tipo y dice de "
             "qué está hecha: esta línea es un título, el bloque de abajo es un "
             "párrafo y el filete del pie es un adorno que no dice nada.\nUn programa "
             "que lea la tarifa en voz alta sigue el orden que da el árbol, no el "
             "orden en que se puso la tinta, y la tabla de la que procede la página "
             "viaja dentro del fichero para que un programa la tome entera.")
        ),
        (
            ("El transporte cuesta 12,40 por envío; la manipulación, 1,85 por paquete;"
             " y el almacenaje, 0,40 por día. Cada gasto se aplica desde el día en que"
             " se acepta el envío.")
        ),
    ),
    foot="Página 1 de 1",
)


# The schedule in Italian.
ITALIAN = Words(
    title="Tariffario, secondo semestre 2026",
    subject=(
        "Un documento che dice di che cosa è fatto e contiene la tabella da cui nasce"
    ),
    lang="it-IT",
    carried_what="Le tariffe indicate in questa pagina, come le legge una macchina",
    heading="Tariffario, secondo semestre 2026",
    paragraphs=(
        (
            ("Questo tariffario dichiara di rispettare la terza parte della norma di "
             "archiviazione al suo livello più alto. Può contenere un file di "
             "qualsiasi tipo e dice di che cosa è fatto: questa riga è un titolo, il "
             "blocco sotto è un paragrafo e il filetto a piè di pagina è un ornamento "
             "che non dice nulla.\nUna sintesi vocale legge il tariffario seguendo "
             "l’ordine dato dall’albero della struttura, non quello in cui è stato "
             "steso l’inchiostro, e la tabella da cui nasce la pagina viaggia dentro "
             "il file, perché un programma la prenda intera.")
        ),
        (
            ("Il trasporto costa 12,40 a spedizione, la movimentazione 1,85 a collo e "
             "il deposito 0,40 al giorno. Una tariffa si applica dal giorno in cui la "
             "spedizione è accettata.")
        ),
    ),
    foot="Pagina 1 di 1",
)


# The schedule in Portuguese.
PORTUGUESE = Words(
    title="Tarifário, segundo semestre de 2026",
    subject="Um documento que diz de que é feito e contém a tabela que lhe dá origem",
    lang="pt-PT",
    carried_what="Os encargos que esta página indica, tal como uma máquina os lê",
    heading="Tarifário, segundo semestre de 2026",
    paragraphs=(
        (
            ("Este tarifário declara cumprir a terceira parte da norma de arquivo, no "
             "seu nível mais alto. Pode conter um ficheiro de qualquer tipo e diz de "
             "que é feito: esta linha é um título, o bloco abaixo é um parágrafo e o "
             "filete do rodapé é um ornamento que nada diz.\nUm programa que lê o "
             "tarifário em voz alta segue a ordem dada pela árvore, e não a ordem em "
             "que a tinta foi posta, e a tabela que dá origem à página viaja dentro do"
             " ficheiro, para que um programa a receba inteira.")
        ),
        (
            ("O transporte custa 12,40 por remessa, o manuseamento 1,85 por volume e a"
             " armazenagem 0,40 por dia. Cada encargo aplica-se a partir do dia em que"
             " a remessa é aceite.")
        ),
    ),
    foot="Página 1 de 1",
)


# The schedule in Dutch.
DUTCH = Words(
    title="Tarievenlijst, tweede helft van 2026",
    subject="Een document dat zegt waaruit het bestaat en de tabel erachter bevat",
    lang="nl-NL",
    carried_what="De tarieven op deze pagina, zoals een machine ze leest",
    heading="Tarievenlijst, tweede helft van 2026",
    paragraphs=(
        (
            ("Deze tarievenlijst verklaart te voldoen aan het derde deel van de "
             "archiefnorm, op het hoogste niveau. Ze mag een bestand van elke soort "
             "bevatten en zegt waaruit ze bestaat: deze regel is een kop, het blok "
             "eronder is een alinea en de lijn onderaan is opsmuk die niets zegt.\nEen"
             " voorleesprogramma houdt de volgorde van de boom aan en niet die waarin "
             "de inkt is neergezet, en de tabel achter de pagina reist mee in het "
             "bestand, zodat een programma haar in zijn geheel kan overnemen.")
        ),
        (
            ("Vervoer kost 12,40 per zending, behandeling 1,85 per pakket en opslag "
             "0,40 per dag. Een tarief geldt vanaf de dag waarop de zending wordt "
             "aanvaard.")
        ),
    ),
    foot="Pagina 1 van 1",
)

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


# Where each block of what the page says goes, in the order it is read: the tag it
# stands under, the size it is set at, the box it goes in, and the leading where it
# states one. The blocks say the heading and the two paragraphs of `Words`, in that
# order.
READ = (
    ("H1", 20.0, 72.0, 782.0, 451.0, None),
    ("P", 11.0, 72.0, 730.0, 451.0, 16.0),
    ("P", 11.0, 72.0, 596.0, 451.0, 16.0),
)

# The rule at the foot of the page, and the box of the line under it. Neither is part of
# the reading, so both are marked as furniture.
RULE = (72.0, 70.0, 451.0, 1.0)
FOOT = (9.0, 72.0, 68.0, 451.0)


def foot_of_page(
    content: hqf_pdf.Content, handle: hqf_pdf.FontHandle, text: str
) -> None:
    """Draws the rule and the page number, both marked as furniture so that
    nothing reading the document aloud says them."""
    left, low, width, height = RULE
    content.begin_artifact(hqf_pdf.Artifact.Footer)
    content.save_state()
    # Rust says this as `set_fill_rgb`; Python takes the colour itself.
    content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
    content.rect(left, low, width, height)
    content.fill()
    content.restore_state()
    content.end_marked()

    size, left, top, width = FOOT
    flow = hqf_pdf.TextFlow(
        handle, size, first_baseline=hqf_pdf.FirstBaseline.points(0.0)
    )
    lines = flow.break_lines(text, width)
    content.begin_artifact(hqf_pdf.Artifact.Footer)
    # The Python side opens and closes the text object itself.
    flow.draw(content, lines, left, top, width)
    content.end_marked()


def sheet(handle: hqf_pdf.FontHandle, words: Words):
    """The one page, and the branch of the tree that says what is on it."""
    content = hqf_pdf.Content()
    marks = hqf_pdf.Marks()
    branches = []

    said = (words.heading, words.paragraphs[0], words.paragraphs[1])
    for (tag, size, left, top, width, leading), text in zip(READ, said):
        settings = {} if leading is None else {"leading": leading}
        flow = hqf_pdf.TextFlow(
            handle,
            size,
            first_baseline=hqf_pdf.FirstBaseline.points(0.0),
            **settings,
        )
        lines = flow.break_lines(text, width)
        runs = flow.draw_tagged(content, lines, left, top, width, tag, marks)
        branches.append(
            hqf_pdf.StructElement(tag, children=[(0, run) for run in runs])
        )

    foot_of_page(content, handle, words.foot)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    return page, hqf_pdf.StructElement("Sect", children=branches)


def main() -> None:
    """Writes the file, and says where it went."""
    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
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(Path(_language.file_name("pdfa3a.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_conformance(hqf_pdf.PdfA.A3A)
    document.set_metadata(
        hqf_pdf.Metadata(
            title=words.title,
            author=AUTHOR,
            subject=words.subject,
            producer=PRODUCER,
            created=ISSUED,
        )
    )
    document.attach(
        hqf_pdf.Attachment(
            CARRIED_NAME,
            words.carried_what,
            CARRIED_TYPE,
            hqf_pdf.Relationship.Data,
            CHANGED,
            CARRIED.encode(),
        )
    )

    handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
    page, sect = sheet(handle, words)
    document.add_page(page)
    document.set_structure(
        hqf_pdf.StructureTree(
            children=[hqf_pdf.StructElement("Document", children=[sect])],
            lang=words.lang,
        )
    )

    data = document.to_bytes()
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_bytes(data)
    print(f"wrote {out}: {len(data)} bytes")


if __name__ == "__main__":
    main()
