"""Writes an archival cover sheet whose metadata carries fields of its own: a
records office's reference, department, retention date and classification.

The Python twin of the `write_own_schema` example in Rust: the same document,
through the binding rather than through the library directly.

PDF/A accepts metadata no standard ever heard of, but not silently. A property
from outside the standard schemas travels with a description of itself — what it
is called, how it is to be read, who it is written for, and what it means — or
the file is not conformant. One schema says all of that, and the library writes
both halves: the properties into the packet, the description into the extension
block.

The page prints the very fields the packet declares, from one list read twice, so
that what a person reads and what a machine reads cannot drift apart.

The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which
set the sheet is drawn up in. The names the properties are written under are not
words: they are what a machine looks them up by, and they are spelled the same
way whoever reads the sheet. What each of them says and what each of them means
are words, and travel into the packet with the page.

A second page declares a second schema, a loan record, whose six fields are read the
six other ways a property may be: as a yes or no, a media type, a proper name, a real
number, an identifier and an address, and two lists: the witnesses to the loan, in no
order, and its changes of hands, in order, each a structure of the record's own
invention that the extension block describes field by field, and the conditions of the
loan, one text in three languages, each marked with its language. It states the keywords
the document carries, when it changed and whether it was trapped, that date as PDF
writes it and read back, and weighs the packet the page carries of its own against the
same facts claiming three standards.

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

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import NamedTuple

import _language
import _licence
import _out

import hqf_pdf

# When the sheet was drawn up. The library never reads the clock, so the caller says
# when.
ISSUED = "2026-07-14T09:30:00+02:00"

# The namespace the office's properties live in. It is the office's own, and resolves to
# nothing: a namespace names a set of properties, it is not an address anything fetches.
NAMESPACE = "https://hqf-pdf.example/ns/records/1.0/"

# The prefix the office's properties are written with.
PREFIX = "rec"

# The namespace the loan record's properties live in.
LOAN_NAMESPACE = "https://hqf-pdf.example/ns/loans/1.0/"

# The prefix the loan record's properties are written with.
LOAN_PREFIX = "loan"

# When the sheet last changed.
CHANGED = "2026-09-17T14:05:00+02:00"

# The loan record's fields: what each is written under, how a validator is to read it,
# and what it says, which is the same in every language.
LOAN_FIELDS = (
    ("Sealed", hqf_pdf.XmpValueType.Boolean, "True"),
    ("Format", hqf_pdf.XmpValueType.MimeType, "application/pdf"),
    ("Custodian", hqf_pdf.XmpValueType.ProperName, "HQF Development"),
    ("ShelfMetres", hqf_pdf.XmpValueType.Real, "1.5"),
    ("Series", hqf_pdf.XmpValueType.Uri, "https://hqf-pdf.com/records/series/42"),
    ("Catalogue", hqf_pdf.XmpValueType.Url, "https://hqf-pdf.com/records/catalogue"),
)

# The namespace the fields of a change of hands live in.
MOVEMENT_NAMESPACE = "https://hqf-pdf.example/ns/loans/movement/1.0/"

# The prefix the fields of a change of hands are written with.
MOVEMENT_PREFIX = "mvt"

# Who witnessed the loan, in no particular order.
WITNESSES = ("Claire Martin", "Jan de Vries")

# The conditions of the loan, one text in three languages: each as its language and its
# text, the one a reader takes by default first.
CONDITIONS = (
    ("x-default", "To be returned unopened by 31 December 2026"),
    ("fr", "À rendre sans l’ouvrir, au plus tard le 31 décembre 2026"),
    ("de", "Ungeöffnet bis zum 31. Dezember 2026 zurückzugeben"),
)

# Each change of hands, in order: the day, and who took the dossier.
MOVEMENTS = (
    ("2026-09-01", "Claire Martin"),
    ("2026-09-17", "HQF Development"),
)


class Field(NamedTuple):
    """One field of the office's own: what it is written under, how a validator is to
    read it, and who it is written for.

    What it says and what it means are words, and stand in `Words` under the same order.
    """

    name: str
    value_type: hqf_pdf.XmpValueType
    category: hqf_pdf.XmpCategory


# The fields the sheet carries. The page draws them and the packet declares them, from
# this one list.
FIELDS = (
    Field("Reference", hqf_pdf.XmpValueType.Text, hqf_pdf.XmpCategory.External),
    Field("Department", hqf_pdf.XmpValueType.Text, hqf_pdf.XmpCategory.External),
    Field("RetainUntil", hqf_pdf.XmpValueType.Date, hqf_pdf.XmpCategory.Internal),
    Field(
        "Classification", hqf_pdf.XmpValueType.Text, hqf_pdf.XmpCategory.External
    ),
    Field("Sheets", hqf_pdf.XmpValueType.Integer, hqf_pdf.XmpCategory.Internal),
)


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

    # What the sheet is called, on the page and in the file's own title.
    title: str
    # The paragraph under the title.
    prose: str
    # The heading over what the sheet says, and the one over what the packet declares of
    # it.
    headings: tuple[str, str]
    # What this sheet says for each field of `FIELDS`. A reference, a date and a count
    # are not words; a department and how widely a dossier may be circulated are.
    values: tuple[str, str, str, str, str]
    # What each field of `FIELDS` means, which is what the packet carries beside it so
    # that a validator will take it.
    descriptions: tuple[str, str, str, str, str]
    # The note at the foot of the sheet.
    note: str
    # What the records office calls its own metadata, for a person reading the packet.
    schema: str
    # What the file says it is about.
    subject: str
    # The second page's heading.
    more_title: str
    # The paragraph under it.
    more_prose: str
    # What the loan record calls its schema.
    loan_schema: str
    # What each field of the loan record means.
    loan_descriptions: tuple[str, str, str, str, str, str]
    # What the loan record's two lists mean: the witnesses, then the changes of hands.
    loan_lists: tuple[str, str, str]
    # What a change of hands is, then what each of its two fields means: the day, and
    # who took the dossier.
    movement: tuple[str, str, str]
    # What the schema is declared under; `{namespace}` and `{prefix}` stand for them.
    declared: str
    # The keywords the document carries.
    keywords: str
    # What the document states of itself; `{keywords}`, `{modified}` and `{trapped}`
    # stand for them.
    states: str
    # Whether a document was trapped: yes, no, not known.
    trapped: tuple[str, str, str]
    # The date of change both ways; `{pdf}` and `{iso}` stand for them.
    dates: str
    # What the packets weigh; `{page}` and `{claimed}` stand for them.
    packets: str

    def document_title(self) -> str:
        """What the file calls itself: what the sheet is, then the reference it is filed
        under."""
        return f"{self.title} {self.values[0]}"

    def movement_type(self) -> hqf_pdf.XmpStructType:
        """The structure a change of hands is written as: the day, and who took the
        dossier."""
        about, when, holder = self.movement
        return hqf_pdf.XmpStructType(
            "Movement",
            MOVEMENT_NAMESPACE,
            MOVEMENT_PREFIX,
            about,
            [
                hqf_pdf.XmpField("When", hqf_pdf.XmpValueType.Date, when),
                hqf_pdf.XmpField("Holder", hqf_pdf.XmpValueType.ProperName, holder),
            ],
        )

    def loan_record(self) -> hqf_pdf.XmpSchema:
        """The loan record's schema: its six fields of one value each, then the
        witnesses as a list in no order and the changes of hands as a list in order."""
        properties = [
            hqf_pdf.XmpProperty(name, value, description, value_type=value_type)
            for (name, value_type, value), description in zip(
                LOAN_FIELDS, self.loan_descriptions
            )
        ]
        witnesses, movements, conditions = self.loan_lists
        properties.append(
            hqf_pdf.XmpProperty(
                "Witnesses",
                hqf_pdf.XmpValue.bag(list(WITNESSES)),
                witnesses,
                value_type=hqf_pdf.XmpType.bag(hqf_pdf.XmpValueType.ProperName),
            )
        )
        changes = hqf_pdf.XmpValue.seq(
            [
                hqf_pdf.XmpValue.structure([("When", when), ("Holder", holder)])
                for when, holder in MOVEMENTS
            ]
        )
        properties.append(
            hqf_pdf.XmpProperty(
                "Movements",
                changes,
                movements,
                value_type=hqf_pdf.XmpType.seq(self.movement_type()),
            )
        )
        properties.append(
            hqf_pdf.XmpProperty(
                "Conditions",
                hqf_pdf.XmpValue.lang_alt(list(CONDITIONS)),
                conditions,
                value_type=hqf_pdf.XmpType.lang_alt(),
            )
        )
        return hqf_pdf.XmpSchema(
            self.loan_schema, LOAN_NAMESPACE, LOAN_PREFIX, properties
        )

    def declared_schema(self) -> hqf_pdf.XmpSchema:
        """The schema the packet declares, built from the fields the page draws."""
        properties = [
            hqf_pdf.XmpProperty(
                field.name,
                value,
                description,
                value_type=field.value_type,
                category=field.category,
            )
            for field, value, description in zip(
                FIELDS, self.values, self.descriptions
            )
        ]
        return hqf_pdf.XmpSchema(self.schema, NAMESPACE, PREFIX, properties)


# The sheet in English.
ENGLISH = Words(
    title="Records office cover sheet",
    prose=(
        "The fields below are the records office's own. No part of the PDF standard "
        "knows what a retention date is, so the file explains itself: each field "
        "arrives in the metadata packet with its name, the way it is to be read, who "
        "it is written for, and what it means. An archival validator accepts them on "
        "that description, and refuses metadata that turns up without one."
    ),
    headings=(
        "What the sheet says",
        "What the packet declares of each of them",
    ),
    values=(
        "RO-2026-004318",
        "Planning",
        "2056-12-31T23:59:59+01:00",
        "Public",
        "1",
    ),
    descriptions=(
        "The reference the records office files the dossier under",
        "The department the dossier came from",
        "The date the dossier may be destroyed, and not before",
        "How widely the dossier may be circulated",
        "How many sheets the dossier holds",
    ),
    note=(
        "Every value above is written twice: once on this page, and once in the packet "
        "a machine reads, under the prefix the schema names. Reading the file's "
        "metadata gives back this table, field for field."
    ),
    schema="Records Office Schema",
    subject="An archival sheet carrying metadata of its own",
    more_title="What else a packet can carry",
    more_prose=(
        "A second schema, the loan record's, carries fields of the six other kinds a "
        "property may be read as, and two lists: the witnesses to the loan, in no "
        "particular order, and each change of hands, in order, which is a structure "
        "the packet describes field by field. The conditions of the loan are one text "
        "in three languages, each version marked with its language. The document "
        "states its keywords, when it changed and whether it was trapped, and this "
        "page carries a packet of its own."
    ),
    loan_schema="Loan Record Schema",
    loan_descriptions=(
        "Whether the dossier left the office sealed",
        "The media type the dossier is lent in",
        "Who holds the dossier while it is out",
        "How much shelf the dossier takes, in metres",
        "The series the dossier belongs to",
        "Where the office's catalogue is read",
    ),
    loan_lists=(
        "Who witnessed the loan",
        "Each time the dossier changed hands, in order",
        "The conditions of the loan, in each language they were agreed in",
    ),
    movement=(
        "One change of hands of a dossier",
        "The day the dossier changed hands",
        "Who took the dossier",
    ),
    declared="Declared in the namespace {namespace}, under the prefix {prefix}:",
    keywords="archive, planning, retention",
    states=(
        "The document's keywords: {keywords}; it changed on {modified}; trapped: "
        "{trapped}."
    ),
    trapped=(
        "yes",
        "no",
        "not known",
    ),
    dates="That date as PDF writes it: {pdf}; read back: {iso}.",
    packets=(
        "This page carries a packet of {page} bytes of its own; the same facts "
        "claiming PDF/A-3b, PDF/UA-1 and PDF/X-4 would weigh {claimed} bytes."
    ),
)

# The sheet in French.
FRENCH = Words(
    title="Bordereau du service d’archives",
    prose=(
        "Les champs ci-dessous sont propres au service d’archives. Aucune partie de la "
        "norme PDF ne sait ce qu’est une date de conservation : le fichier s’explique "
        "donc lui-même. Chaque champ arrive dans le paquet de métadonnées avec son "
        "nom, la façon de le lire, le public auquel il s’adresse et son sens. Un "
        "validateur d’archivage les accepte sur cette description, et refuse toute "
        "métadonnée qui en est dépourvue."
    ),
    headings=(
        "Ce que dit le bordereau",
        "Ce que le paquet déclare pour chacun",
    ),
    values=(
        "RO-2026-004318",
        "Urbanisme",
        "2056-12-31T23:59:59+01:00",
        "Public",
        "1",
    ),
    descriptions=(
        "La référence sous laquelle le service d’archives classe le dossier",
        "Le service d’où vient le dossier",
        "La date à partir de laquelle le dossier peut être détruit",
        "Le périmètre de diffusion du dossier",
        "Le nombre de feuilles du dossier",
    ),
    note=(
        "Chaque valeur ci-dessus est écrite deux fois : une fois sur cette page, une "
        "fois dans le paquet que lit une machine, sous le préfixe que nomme le schéma. "
        "Lire les métadonnées du fichier restitue ce tableau, champ pour champ."
    ),
    schema="Schéma du service d’archives",
    subject="Un bordereau d’archives doté de ses propres métadonnées",
    more_title="Ce qu’un paquet peut encore contenir",
    more_prose=(
        "Un second schéma, celui de la fiche de prêt, contient des champs de chacun "
        "des six autres types de valeur qu’une propriété peut prendre, ainsi que deux "
        "listes : les témoins du prêt, sans ordre particulier, et les passages du "
        "dossier d’une main à l’autre, dans l’ordre. Chaque passage est une structure "
        "que le paquet décrit champ par champ. Les conditions du prêt forment un seul "
        "texte en trois langues, dont chaque version indique sa langue. Le document "
        "indique ses mots-clés, sa date de modification et s’il a fait l’objet d’un "
        "recouvrement, et cette page contient son propre paquet."
    ),
    loan_schema="Schéma de la fiche de prêt",
    loan_descriptions=(
        "Si le dossier a quitté le service sous scellés",
        "Le type de média sous lequel le dossier est prêté",
        "Qui détient le dossier pendant le prêt",
        "La longueur de rayonnage du dossier, en mètres",
        "La série à laquelle appartient le dossier",
        "L’adresse où se consulte le catalogue du service",
    ),
    loan_lists=(
        "Qui a été témoin du prêt",
        "Chaque passage du dossier d’une main à l’autre, dans l’ordre",
        "Les conditions du prêt, une version par langue",
    ),
    movement=(
        "Un passage du dossier d’une main à l’autre",
        "Le jour où le dossier a changé de mains",
        "Qui a reçu le dossier",
    ),
    declared="Déclaré dans l’espace de noms {namespace}, sous le préfixe {prefix} :",
    keywords="archives, urbanisme, conservation",
    states=(
        "Mots-clés du document : {keywords} ; modifié le {modified} ; recouvrement : "
        "{trapped}."
    ),
    trapped=(
        "oui",
        "non",
        "inconnu",
    ),
    dates="Cette date telle que l’écrit le PDF : {pdf} ; relue : {iso}.",
    packets=(
        "Cette page contient son propre paquet de {page} octets ; les mêmes "
        "informations, déclarant la conformité à PDF/A-3b, PDF/UA-1 et PDF/X-4, "
        "pèseraient {claimed} octets."
    ),
)

# The sheet in Dutch.
DUTCH = Words(
    title="Voorblad van het dossierarchief",
    prose=(
        "De velden hieronder zijn die van het dossierarchief zelf. Geen deel van de "
        "PDF-norm weet wat een bewaardatum is, dus legt het bestand zichzelf uit: elk "
        "veld komt in het metadatapakket met zijn naam, de manier waarop het gelezen "
        "moet worden, voor wie het geschreven is en wat het betekent. Een "
        "archiefvalidator aanvaardt ze op die beschrijving, en weigert metadata die "
        "zonder beschrijving opduikt."
    ),
    headings=(
        "Wat het blad zegt",
        "Wat het pakket van elk ervan verklaart",
    ),
    values=(
        "RO-2026-004318",
        "Ruimtelijke ordening",
        "2056-12-31T23:59:59+01:00",
        "Openbaar",
        "1",
    ),
    descriptions=(
        "Het kenmerk waaronder het archief het dossier opbergt",
        "De afdeling waar het dossier vandaan kwam",
        "De datum waarop het dossier vernietigd mag worden, en niet eerder",
        "Hoe ruim het dossier verspreid mag worden",
        "Hoeveel bladen het dossier bevat",
    ),
    note=(
        "Elke waarde hierboven is twee keer geschreven: één keer op deze pagina en "
        "één keer in het pakket dat een machine leest, onder het voorvoegsel dat het "
        "schema noemt. De metadata van het bestand lezen geeft deze tabel terug, veld "
        "voor veld."
    ),
    schema="Schema van het dossierarchief",
    subject="Een archiefblad met eigen metadata",
    more_title="Wat een pakket nog meer kan bevatten",
    more_prose=(
        "Een tweede schema, dat van het uitleenregister, bevat velden van de zes "
        "andere soorten waarin een eigenschap gelezen kan worden, en twee lijsten: de "
        "getuigen van de uitlening, in willekeurige volgorde, en elke keer dat het "
        "dossier van hand wisselde, op volgorde, als een structuur die het pakket veld "
        "voor veld beschrijft. De voorwaarden van de uitlening zijn één tekst in drie "
        "talen, elke versie gemerkt met haar taal. Het document noemt zijn "
        "trefwoorden, wanneer het veranderde en of het getrapt is, en deze pagina "
        "heeft een eigen pakket."
    ),
    loan_schema="Schema van het uitleenregister",
    loan_descriptions=(
        "Of het dossier verzegeld het archief verliet",
        "Het mediatype waarin het dossier wordt uitgeleend",
        "Wie het dossier heeft terwijl het weg is",
        "Hoeveel plankruimte het dossier inneemt, in meters",
        "De reeks waartoe het dossier behoort",
        "Waar de catalogus van het archief te lezen is",
    ),
    loan_lists=(
        "Wie de uitlening als getuige bijwoonde",
        "Elke keer dat het dossier van hand wisselde, op volgorde",
        "De voorwaarden van de uitlening, in elke taal waarin ze zijn afgesproken",
    ),
    movement=(
        "Eén keer dat een dossier van hand wisselde",
        "De dag waarop het dossier van hand wisselde",
        "Wie het dossier overnam",
    ),
    declared="Gedeclareerd in de naamruimte {namespace}, onder het voorvoegsel {prefix}:",
    keywords="archief, ruimtelijke ordening, bewaring",
    states=(
        "De trefwoorden van het document: {keywords}; het veranderde op {modified}; "
        "getrapt: {trapped}."
    ),
    trapped=(
        "ja",
        "nee",
        "onbekend",
    ),
    dates="Die datum zoals PDF hem schrijft: {pdf}; teruggelezen: {iso}.",
    packets=(
        "Deze pagina heeft een eigen pakket van {page} bytes; dezelfde gegevens met "
        "een claim op PDF/A-3b, PDF/UA-1 en PDF/X-4 zouden {claimed} bytes wegen."
    ),
)

# The sheet in Portuguese.
PORTUGUESE = Words(
    title="Folha de rosto do arquivo de processos",
    prose=(
        "Os campos abaixo são próprios do arquivo de processos. Nenhuma parte da "
        "norma PDF sabe o que é uma data de conservação, por isso o ficheiro "
        "explica-se a si mesmo: cada campo chega ao pacote de metadados com o seu "
        "nome, a forma de o ler, para quem é escrito e o que significa. Um validador "
        "de arquivo aceita-os com essa descrição, e recusa os metadados que chegam "
        "sem ela."
    ),
    headings=(
        "O que a folha diz",
        "O que o pacote declara de cada um",
    ),
    values=(
        "RO-2026-004318",
        "Urbanismo",
        "2056-12-31T23:59:59+01:00",
        "Público",
        "1",
    ),
    descriptions=(
        "A referência com que o arquivo regista o processo",
        "O serviço de onde vem o processo",
        "A data a partir da qual o processo pode ser destruído, e não antes",
        "Com que amplitude o processo pode circular",
        "Quantas folhas tem o processo",
    ),
    note=(
        "Cada valor acima é escrito duas vezes: uma nesta página e outra no pacote "
        "que uma máquina lê, com o prefixo que o esquema nomeia. Ler os metadados do "
        "ficheiro devolve esta tabela, campo a campo."
    ),
    schema="Esquema do arquivo de processos",
    subject="Uma folha de arquivo com metadados próprios",
    more_title="Que mais um pacote pode levar",
    more_prose=(
        "Um segundo esquema, o do registo de empréstimos, leva campos dos outros seis "
        "tipos em que uma propriedade pode ser lida, e duas listas: as testemunhas do "
        "empréstimo, sem ordem definida, e cada mudança de mãos do processo, por "
        "ordem, sob a forma de uma estrutura que o pacote descreve campo a campo. As "
        "condições do empréstimo são um único texto em três línguas, cada versão "
        "marcada com a sua língua. O documento indica as suas palavras-chave, quando "
        "mudou e se foi submetido a trapping, e esta página leva um pacote próprio."
    ),
    loan_schema="Esquema do registo de empréstimos",
    loan_descriptions=(
        "Se o processo saiu do arquivo selado",
        "O tipo de suporte em que o processo é emprestado",
        "Quem tem o processo enquanto está fora",
        "Quanta prateleira ocupa o processo, em metros",
        "A série a que o processo pertence",
        "Onde se consulta o catálogo do arquivo",
    ),
    loan_lists=(
        "Quem testemunhou o empréstimo",
        "Cada vez que o processo mudou de mãos, por ordem",
        "As condições do empréstimo, em cada língua em que foram acordadas",
    ),
    movement=(
        "Uma mudança de mãos de um processo",
        "O dia em que o processo mudou de mãos",
        "Quem recebeu o processo",
    ),
    declared="Declarado no espaço de nomes {namespace}, com o prefixo {prefix}:",
    keywords="arquivo, urbanismo, conservação",
    states=(
        "As palavras-chave do documento: {keywords}; mudou em {modified}; trapping: "
        "{trapped}."
    ),
    trapped=(
        "sim",
        "não",
        "desconhecido",
    ),
    dates="Essa data como o PDF a escreve: {pdf}; relida: {iso}.",
    packets=(
        "Esta página leva um pacote próprio de {page} bytes; os mesmos dados a "
        "declarar PDF/A-3b, PDF/UA-1 e PDF/X-4 pesariam {claimed} bytes."
    ),
)

# The sheet in Italian.
ITALIAN = Words(
    title="Frontespizio dell’archivio atti",
    prose=(
        "I campi qui sotto sono propri dell’archivio atti. Nessuna parte della norma "
        "PDF sa cos’è una data di conservazione, così il file si spiega da sé: ogni "
        "campo arriva nel pacchetto di metadati con il suo nome, il modo di leggerlo, "
        "per chi è scritto e cosa significa. Un validatore d’archivio li accetta su "
        "quella descrizione, e rifiuta i metadati che arrivano senza."
    ),
    headings=(
        "Cosa dice il foglio",
        "Cosa dichiara il pacchetto di ciascuno",
    ),
    values=(
        "RO-2026-004318",
        "Urbanistica",
        "2056-12-31T23:59:59+01:00",
        "Pubblico",
        "1",
    ),
    descriptions=(
        "Il riferimento con cui l’archivio registra la pratica",
        "Il servizio da cui proviene la pratica",
        "La data da cui la pratica può essere distrutta, e non prima",
        "Quanto largamente può circolare la pratica",
        "Quanti fogli contiene la pratica",
    ),
    note=(
        "Ogni valore qui sopra è scritto due volte: una su questa pagina e una nel "
        "pacchetto che legge una macchina, con il prefisso che nomina lo schema. "
        "Leggere i metadati del file restituisce questa tabella, campo per campo."
    ),
    schema="Schema dell’archivio atti",
    subject="Un foglio d’archivio che porta metadati propri",
    more_title="Cos’altro può portare un pacchetto",
    more_prose=(
        "Un secondo schema, quello del registro dei prestiti, porta campi degli altri "
        "sei tipi in cui si può leggere una proprietà, e due elenchi: i testimoni del "
        "prestito, in ordine sparso, e ogni passaggio di mano della pratica, in "
        "ordine, sotto forma di una struttura che il pacchetto descrive campo per "
        "campo. Le condizioni del prestito sono un unico testo in tre lingue, ogni "
        "versione contrassegnata dalla sua lingua. Il documento indica le sue parole "
        "chiave, quando è cambiato e se è stato sottoposto a trapping, e questa pagina "
        "porta un pacchetto proprio."
    ),
    loan_schema="Schema del registro dei prestiti",
    loan_descriptions=(
        "Se la pratica è uscita dall’archivio sigillata",
        "Il tipo di supporto in cui la pratica è prestata",
        "Chi tiene la pratica mentre è fuori",
        "Quanto scaffale occupa la pratica, in metri",
        "La serie a cui appartiene la pratica",
        "Dove si consulta il catalogo dell’archivio",
    ),
    loan_lists=(
        "Chi ha assistito al prestito come testimone",
        "Ogni passaggio di mano della pratica, in ordine",
        "Le condizioni del prestito, in ogni lingua in cui sono state concordate",
    ),
    movement=(
        "Un passaggio di mano di una pratica",
        "Il giorno in cui la pratica è passata di mano",
        "Chi ha ricevuto la pratica",
    ),
    declared="Dichiarato nello spazio dei nomi {namespace}, con il prefisso {prefix}:",
    keywords="archivio, urbanistica, conservazione",
    states=(
        "Le parole chiave del documento: {keywords}; è cambiato il {modified}; "
        "trapping: {trapped}."
    ),
    trapped=(
        "sì",
        "no",
        "sconosciuto",
    ),
    dates="Quella data come la scrive PDF: {pdf}; riletta: {iso}.",
    packets=(
        "Questa pagina porta un pacchetto proprio di {page} byte; gli stessi dati che "
        "dichiarano PDF/A-3b, PDF/UA-1 e PDF/X-4 peserebbero {claimed} byte."
    ),
)

# The sheet in Spanish.
SPANISH = Words(
    title="Portada del archivo de expedientes",
    prose=(
        "Los campos de abajo son propios del archivo de expedientes. Ninguna parte de "
        "la norma PDF sabe qué es una fecha de conservación, así que el archivo se "
        "explica solo: cada campo llega al paquete de metadatos con su nombre, la "
        "forma de leerlo, para quién se escribe y qué significa. Un validador de "
        "archivo los acepta con esa descripción, y rechaza los metadatos que llegan "
        "sin ella."
    ),
    headings=(
        "Lo que dice la hoja",
        "Lo que el paquete declara de cada uno",
    ),
    values=(
        "RO-2026-004318",
        "Urbanismo",
        "2056-12-31T23:59:59+01:00",
        "Público",
        "1",
    ),
    descriptions=(
        "La referencia con que el archivo registra el expediente",
        "El servicio del que procede el expediente",
        "La fecha a partir de la cual el expediente puede destruirse, y no antes",
        "Con qué amplitud puede circular el expediente",
        "Cuántas hojas tiene el expediente",
    ),
    note=(
        "Cada valor de arriba se escribe dos veces: una en esta página y otra en el "
        "paquete que lee una máquina, con el prefijo que nombra el esquema. Leer los "
        "metadatos del archivo devuelve esta tabla, campo por campo."
    ),
    schema="Esquema del archivo de expedientes",
    subject="Una hoja de archivo con metadatos propios",
    more_title="Qué más puede llevar un paquete",
    more_prose=(
        "Un segundo esquema, el del registro de préstamos, lleva campos de los otros "
        "seis tipos en que puede leerse una propiedad, y dos listas: los testigos del "
        "préstamo, sin un orden concreto, y cada cambio de manos del expediente, por "
        "orden, en forma de una estructura que el paquete describe campo por campo. "
        "Las condiciones del préstamo son un único texto en tres idiomas, cada versión "
        "marcada con su idioma. El documento indica sus palabras clave, cuándo cambió "
        "y si se le aplicó reventado, y esta página lleva un paquete propio."
    ),
    loan_schema="Esquema del registro de préstamos",
    loan_descriptions=(
        "Si el expediente salió del archivo precintado",
        "El tipo de soporte en que se presta el expediente",
        "Quién tiene el expediente mientras está fuera",
        "Cuánto estante ocupa el expediente, en metros",
        "La serie a la que pertenece el expediente",
        "Dónde se consulta el catálogo del archivo",
    ),
    loan_lists=(
        "Quiénes presenciaron el préstamo como testigos",
        "Cada vez que el expediente cambió de manos, por orden",
        "Las condiciones del préstamo, en cada idioma en que se acordaron",
    ),
    movement=(
        "Un cambio de manos de un expediente",
        "El día en que el expediente cambió de manos",
        "Quién recibió el expediente",
    ),
    declared="Declarado en el espacio de nombres {namespace}, con el prefijo {prefix}:",
    keywords="archivo, urbanismo, conservación",
    states=(
        "Las palabras clave del documento: {keywords}; cambió el {modified}; "
        "reventado: {trapped}."
    ),
    trapped=(
        "sí",
        "no",
        "desconocido",
    ),
    dates="Esa fecha tal como la escribe PDF: {pdf}; leída de nuevo: {iso}.",
    packets=(
        "Esta página lleva un paquete propio de {page} bytes; los mismos datos "
        "declarando PDF/A-3b, PDF/UA-1 y PDF/X-4 pesarían {claimed} bytes."
    ),
)

# The sheet in German.
GERMAN = Words(
    title="Deckblatt des Archivamts",
    prose=(
        "Die Felder unten sind die eigenen des Archivamts. Kein Teil der PDF-Norm "
        "weiß, was ein Aufbewahrungsdatum ist, also erklärt sich die Datei selbst: "
        "Jedes Feld kommt im Metadatenpaket mit seinem Namen, der Art, wie es zu "
        "lesen ist, für wen es geschrieben ist und was es bedeutet. Ein "
        "Archivvalidator nimmt sie nach dieser Beschreibung an und lehnt Metadaten "
        "ab, die ohne eine solche auftauchen."
    ),
    headings=(
        "Was das Blatt sagt",
        "Was das Paket zu jedem davon erklärt",
    ),
    values=(
        "RO-2026-004318",
        "Planung",
        "2056-12-31T23:59:59+01:00",
        "Öffentlich",
        "1",
    ),
    descriptions=(
        "Das Zeichen, unter dem das Archivamt die Akte ablegt",
        "Die Abteilung, aus der die Akte stammt",
        "Der Tag, an dem die Akte vernichtet werden darf, und nicht früher",
        "Wie weit die Akte verbreitet werden darf",
        "Wie viele Blätter die Akte enthält",
    ),
    note=(
        "Jeder Wert oben steht zweimal da: einmal auf dieser Seite und einmal in dem "
        "Paket, das eine Maschine liest, unter dem Präfix, das das Schema nennt. Wer "
        "die Metadaten der Datei liest, erhält diese Tabelle zurück, Feld für Feld."
    ),
    schema="Schema des Archivamts",
    subject="Ein Archivblatt mit eigenen Metadaten",
    more_title="Was ein Paket sonst noch tragen kann",
    more_prose=(
        "Ein zweites Schema, das des Ausleihvermerks, trägt Felder der sechs anderen "
        "Arten, als die eine Eigenschaft gelesen werden kann, dazu zwei Listen: die "
        "Zeugen der Ausleihe, ohne bestimmte Reihenfolge, und jede Übergabe der Akte, "
        "der Reihe nach, als Struktur, die das Paket Feld für Feld beschreibt. Die "
        "Bedingungen der Ausleihe sind ein einziger Text in drei Sprachen, jede "
        "Fassung mit ihrer Sprache gekennzeichnet. Das Dokument nennt seine "
        "Schlüsselwörter, wann es geändert wurde und ob es überfüllt wurde, und diese "
        "Seite trägt ein eigenes Paket."
    ),
    loan_schema="Schema des Ausleihvermerks",
    loan_descriptions=(
        "Ob die Akte das Amt versiegelt verlassen hat",
        "Der Medientyp, in dem die Akte verliehen wird",
        "Wer die Akte hat, solange sie außer Haus ist",
        "Wie viele Regalmeter die Akte einnimmt",
        "Die Reihe, zu der die Akte gehört",
        "Wo der Katalog des Amts gelesen wird",
    ),
    loan_lists=(
        "Wer die Ausleihe bezeugt hat",
        "Jede Übergabe der Akte, der Reihe nach",
        "Die Bedingungen der Ausleihe, in jeder Sprache, in der sie vereinbart wurden",
    ),
    movement=(
        "Eine Übergabe einer Akte",
        "Der Tag, an dem die Akte übergeben wurde",
        "Wer die Akte übernommen hat",
    ),
    declared="Im Namensraum {namespace} erklärt, unter dem Präfix {prefix}:",
    keywords="Archiv, Planung, Aufbewahrung",
    states=(
        "Die Schlüsselwörter des Dokuments: {keywords}; geändert am {modified}; "
        "überfüllt: {trapped}."
    ),
    trapped=(
        "ja",
        "nein",
        "unbekannt",
    ),
    dates="Dieses Datum, wie PDF es schreibt: {pdf}; zurückgelesen: {iso}.",
    packets=(
        "Diese Seite trägt ein eigenes Paket von {page} Bytes; dieselben Angaben mit "
        "dem Anspruch PDF/A-3b, PDF/UA-1 und PDF/X-4 wögen {claimed} Bytes."
    ),
)

# 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 the sheet is set from.
X = 72.0

# The room the sheet has across the page.
WIDTH = 451.0

# How far into that room the values stand, leaving the names to their left.
VALUES = 150.0

# Where the first block starts, down from the top of the page.
TOP = 780.0


def block(
    content: hqf_pdf.Content,
    flow: hqf_pdf.TextFlow,
    text: str,
    top: float,
) -> float:
    """Draws `text` in `flow` at `top`, and hands back the top of whatever follows
    it."""
    lines = flow.break_lines(text, WIDTH)
    flow.draw(content, lines, X, top, WIDTH)
    return top - flow.height(lines)


def cover_sheet(handle: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Page:
    """The sheet: what it is, what it says about itself, and how a reader may check."""
    content = hqf_pdf.Content()

    title = hqf_pdf.TextFlow(handle, 20.0, space_after=14.0)
    prose = hqf_pdf.TextFlow(
        handle,
        10.5,
        leading=15.0,
        align=hqf_pdf.Align.Justify,
        space_after=16.0,
    )
    heading = hqf_pdf.TextFlow(handle, 12.0, space_before=20.0, space_after=8.0)
    row = hqf_pdf.TextFlow(
        handle,
        11.0,
        leading=17.0,
        tab_method=hqf_pdf.TabMethod.Ruler,
        tab_ruler=[VALUES],
    )
    declared = hqf_pdf.TextFlow(handle, 9.5, leading=14.0).hanging_list(0.0, VALUES)
    note = hqf_pdf.TextFlow(handle, 9.0, leading=13.0, space_before=18.0)

    top = block(content, title, words.title, TOP)
    top = block(content, prose, words.prose, top)

    top = block(content, heading, words.headings[0], top)
    values = "\n".join(
        f"{field.name}\t{value}" for field, value in zip(FIELDS, words.values)
    )
    top = block(content, row, values, top)

    top = block(content, heading, words.headings[1], top)
    rows = "\n".join(
        f"{PREFIX}:{field.name}\t{field.value_type.as_str()} · "
        f"{field.category.as_str()} · {description}"
        for field, description in zip(FIELDS, words.descriptions)
    )
    top = block(content, declared, rows, top)

    block(content, note, words.note, top)

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


def shown(value: hqf_pdf.XmpValue) -> str:
    """What `value` says, as the page prints it: text as it stands, the items of a list
    parted by semicolons, each text in several languages after its language and a
    colon, the fields of a structure by commas."""
    if value.kind == "structure":
        return ", ".join(shown(field) for __, field in value.fields)
    if value.kind == "lang_alt":
        return "; ".join(f"{language}: {text}" for language, text in value.languages)
    text = value.as_text()
    if text is not None:
        return text
    return "; ".join(shown(item) for item in value.items)


def second_sheet(handle: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Page:
    """The second page: the loan record's schema read back field by field, with the
    structure a change of hands is written as, what the document states of itself,
    its date of change both ways, and what the packets weigh."""
    content = hqf_pdf.Content()
    title = hqf_pdf.TextFlow(handle, 20.0, space_after=14.0)
    prose = hqf_pdf.TextFlow(
        handle,
        10.5,
        leading=15.0,
        align=hqf_pdf.Align.Justify,
        space_after=16.0,
    )
    declared = hqf_pdf.TextFlow(handle, 9.5, leading=14.0).hanging_list(0.0, VALUES)
    line = hqf_pdf.TextFlow(handle, 10.0, leading=14.0, space_before=10.0)

    top = block(content, title, words.more_title, TOP)
    top = block(content, prose, words.more_prose, top)

    schema = words.loan_record()
    heading = words.declared.replace("{namespace}", schema.namespace).replace(
        "{prefix}", schema.prefix
    )
    top = block(content, line, heading, top)
    movement = words.movement_type()
    rows = "\n".join(
        [
            f"{schema.prefix}:{prop.name}\t{shown(prop.value)} · {prop.value_type} · "
            f"{prop.description}"
            for prop in schema.properties
        ]
        + [f"{movement.name}\t{movement.description}"]
        + [
            f"{MOVEMENT_PREFIX}:{field.name}\t{field.value_type} · {field.description}"
            for field in movement.fields
        ]
    )
    top = block(content, declared, rows, top)

    # The document states no trapping.
    states = (
        words.states.replace("{keywords}", words.keywords)
        .replace("{modified}", CHANGED)
        .replace("{trapped}", words.trapped[2])
    )
    top = block(content, line, states, top)

    written = hqf_pdf.pdf_date(CHANGED)
    dates = words.dates.replace("{pdf}", written).replace(
        "{iso}", hqf_pdf.iso_date(written) or ""
    )
    top = block(content, line, dates, top)

    own = hqf_pdf.Metadata(title=words.more_title)
    page_packet = hqf_pdf.xmp_packet(own)
    claimed = hqf_pdf.xmp_packet(
        own,
        archival=hqf_pdf.PdfA.A3B,
        accessibility=hqf_pdf.PdfUa.One,
        printing=hqf_pdf.PdfX.X4,
    )
    packets = words.packets.replace("{page}", str(len(page_packet))).replace(
        "{claimed}", str(len(claimed))
    )
    block(content, line, packets, top)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    page.set_metadata(hqf_pdf.Xmp.packet(page_packet))
    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("own_schema.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_conformance(hqf_pdf.PdfA.A3B)
    document.set_metadata(
        hqf_pdf.Metadata(
            title=words.document_title(),
            author="Olivier Pons",
            subject=words.subject,
            producer="hqf-pdf",
            created=ISSUED,
            modified=CHANGED,
            keywords=words.keywords,
            schemas=[words.declared_schema(), words.loan_record()],
        )
    )

    handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
    document.add_page(cover_sheet(handle, words))
    document.add_page(second_sheet(handle, words))

    written = document.write(out)
    print(f"wrote {out}: {written} bytes")


if __name__ == "__main__":
    main()
