"""Writes a document carrying a digital signature, made with a demonstration certificate.

The Python twin of the `write_signed` example in Rust: the same document, through the
binding rather than through the library directly. Its page states every command that
made it.

The library assembles the signature but for the one operation the private key performs,
which it hands to a function of the caller's. Here that function runs the `openssl`
program, so the key stays in a file the library never opens:

1. the key and its certificate were made once, from the repository's root, by the
   command KEY_COMMAND states, and are committed under `keys/`;
2. the certificate is handed to the library as DER, which CERTIFICATE_COMMAND writes out
   of the committed PEM file;
3. the library reserves room in the file for the signature, takes the SHA-256 digest of
   every byte around that room, and hands the function the DER of the signed attributes
   naming that digest; the function pipes them to SIGN_COMMAND, whose output is their
   RSA PKCS #1 v1.5 signature;
4. the library wraps that signature and the certificate into the CMS structure of a
   PAdES B-B signature and writes it, in hexadecimal, into the room between the two runs
   of bytes `/ByteRange` names.

CHECK_COMMAND is what checks the file without this library: it is handed the two runs
joined into one file and the structure decoded into another.

The certificate is a demonstration one, trusted by nobody, and its private key is
committed beside it, under `keys/`: the signature shows the file has not changed, and
says nothing about who signed it. A signature made with an RSA key is the same bytes
every time it is made over the same bytes, so the example writes the same file on every
run.

The page is written in the language `HQF_PDF_LANG` names. The commands, the signer's name
and the moment of signing are not: a command is typed as it stands, and the name is the
one the certificate carries.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out
import _signer
from _signer import CERTIFICATE_COMMAND, CHECK_COMMAND, SIGN_COMMAND, SIGNER

import hqf_pdf

# The command that made the demonstration key and its certificate, as the page sets it
# over three lines. The example does not run it: its output is committed.
KEY_COMMAND = (
    "openssl req -x509 -newkey rsa:2048 -nodes -days 3650",
    '    -subj "/CN=hqf-pdf demonstration signer"',
    "    -keyout keys/demonstration_signer.key -out keys/demonstration_signer.crt",
)

# When the document is signed, as the signature states it.
SIGNED_AT = "2026-09-13T08:00:00+00:00"

# The same moment, as the box on the page shows it.
SIGNED_AT_SHOWN = "2026-09-13 08:00 UTC"

# The name of the signature field.
FIELD = "approval"

# How far in from the left edge of the sheet every line is set, in points.
LEFT = 72.0

# Where the baseline of the heading sits, in points up from the foot of the sheet.
HEADING_BASELINE = 770.0

# The size the heading is set at, in points.
HEADING_SIZE = 18.0

# The size the body and the steps are set at, in points.
BODY_SIZE = 10.5

# The size a section heading is set at, in points.
SECTION_SIZE = 13.0

# The size a command is set at, in points.
COMMAND_SIZE = 8.5

# The signature box, under the body: its lower-left corner, its width and its height, in
# points.
BOX = (LEFT, 579.0, 260.0, 44.0)

# How far the heading over the steps sits below the last line of the body, the signature
# box standing between the two, in points.
PAST_THE_BOX = 92.0

# The size the lines in the signature box are set at, in points.
BOX_SIZE = 9.0

# The grey of the frame around the signature box, and its width in points.
BORDER = hqf_pdf.Rgb.gray(0.55)
BORDER_WIDTH = 0.75

# What a line of the page is, which sets its size and how far it sits below the line
# before it.
HEADING = "heading"
BODY = "body"
PARAGRAPH = "paragraph"
SECTION = "section"
STEP = "step"
STEP_CARRIED_ON = "step carried on"
COMMAND = "command"


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

    The commands, the signer's name and the moment of signing are not among them.
    """

    # What the document is called, at the head of the page and in what the file says of
    # itself.
    title: str
    # What the signature covers.
    covers: tuple[str, ...]
    # What a demonstration certificate proves, and what it does not.
    proves: tuple[str, ...]
    # Why the document was signed, as the signature states it.
    reason: str
    # What stands before the moment of signing in the signature box.
    signed_label: str
    # What stands over the steps that made the signature.
    made_heading: str
    # The first step: the key and its certificate.
    made_key: str
    # The second step: the certificate as DER.
    made_certificate: str
    # The third step: what the key signs.
    made_signature: tuple[str, ...]
    # The fourth step: where the signature lands in the file.
    made_structure: tuple[str, ...]
    # What stands over the way to check the file.
    check_heading: str
    # What to hand the check.
    check: tuple[str, ...]


# The page in English.
ENGLISH = Words(
    title="A signed document, and how it was signed",
    covers=(
        "This file carries a digital signature. It covers every byte of the file",
        "but the place it is written in: one byte changed anywhere breaks it, and",
        "reading software says so.",
    ),
    proves=(
        "The certificate is a demonstration one: it was made for this example,",
        "and it names no person and no company. The signature proves the file",
        "has not changed; it proves nothing about who signed it, since nobody",
        "vouches for this certificate.",
    ),
    reason="Shows how a document is signed",
    signed_label="Signed",
    made_heading="How it was signed",
    made_key="1. The key and its certificate were made once, from the repository's root:",
    made_certificate="2. The library is handed the certificate as DER, which this writes:",
    made_signature=(
        "3. The library leaves room in the file for the signature, takes the digest",
        "of every byte around it, and hands the program the attributes to sign.",
        "The key signs them, and never reaches the library:",
    ),
    made_structure=(
        "4. The library wraps that signature and the certificate into the structure",
        "a PAdES signature carries, and writes it into the room it left.",
    ),
    check_heading="Checking it without this library",
    check=(
        "The file's /ByteRange names the two runs of bytes the signature covers,",
        "and /Contents holds the structure between them, in hexadecimal. Join",
        "the two runs into covered.bin, decode the structure into signature.der,",
        "and run:",
    ),
)

# The page in French.
FRENCH = Words(
    title="Un document signé, et comment il l’a été",
    covers=(
        "Ce fichier contient une signature numérique. Elle couvre chaque octet du",
        "fichier, sauf l’endroit où elle est écrite : un seul octet modifié, où que",
        "ce soit, la rompt, et le logiciel de lecture le signale.",
    ),
    proves=(
        "Le certificat est un certificat de démonstration : il a été créé pour",
        "cet exemple, et ne nomme ni personne ni entreprise. La signature",
        "prouve que le fichier n’a pas changé ; elle ne dit rien de l’identité",
        "du signataire, puisque personne ne se porte garant de ce certificat.",
    ),
    reason="Montre comment un document est signé",
    signed_label="Signé le",
    made_heading="Comment il a été signé",
    made_key=("1. La clé et son certificat ont été générés une fois, depuis la racine "
              "du dépôt :"),
    made_certificate=("2. La bibliothèque reçoit le certificat en DER, produit par "
                      "cette commande :"),
    made_signature=(
        "3. La bibliothèque réserve dans le fichier la place de la signature, calcule",
        "l’empreinte de tous les octets autour, et remet au programme les attributs à",
        "signer. La clé les signe sans jamais entrer dans la bibliothèque :",
    ),
    made_structure=(
        "4. La bibliothèque enveloppe cette signature et le certificat dans la",
        "structure que prévoit une signature PAdES, et l’écrit dans la place réservée.",
    ),
    check_heading="Le vérifier sans cette bibliothèque",
    check=(
        "Le /ByteRange du fichier désigne les deux plages d’octets que la signature",
        ("couvre, et /Contents contient la structure placée entre elles, en "
         "hexadécimal."),
        "Concaténez les deux plages dans covered.bin, décodez la structure dans",
        "signature.der, puis lancez :",
    ),
)

# The page in Dutch.
DUTCH = Words(
    title="Een ondertekend document, en hoe dat ging",
    covers=(
        "Dit bestand bevat een digitale handtekening. Die dekt elke byte van het bestand",
        "behalve de plek waar ze zelf staat: één gewijzigde byte maakt haar ongeldig, en",
        "leessoftware zegt dat.",
    ),
    proves=(
        "Het certificaat is een demonstratiecertificaat: het is voor dit voorbeeld gemaakt,",
        "en het noemt geen persoon of bedrijf. De handtekening bewijst dat het bestand",
        "niet veranderd is; ze bewijst niets over wie tekende, want niemand",
        "staat in voor dit certificaat.",
    ),
    reason="Toont hoe een document ondertekend wordt",
    signed_label="Ondertekend",
    made_heading="Hoe het ondertekend is",
    made_key="1. Sleutel en certificaat zijn één keer gemaakt, in de hoofdmap van de repository:",
    made_certificate="2. De bibliotheek krijgt het certificaat als DER, dat dit schrijft:",
    made_signature=(
        "3. De bibliotheek laat ruimte in het bestand voor de handtekening, berekent de hash",
        "van elke byte eromheen en geeft het programma de attributen om te ondertekenen.",
        "De sleutel ondertekent ze, en bereikt de bibliotheek nooit:",
    ),
    made_structure=(
        "4. De bibliotheek verpakt die handtekening en het certificaat in de structuur",
        "die een PAdES-handtekening bevat, en schrijft die in de vrijgelaten ruimte.",
    ),
    check_heading="Controleren zonder deze bibliotheek",
    check=(
        "De /ByteRange noemt de twee bytereeksen die de handtekening dekt,",
        "en /Contents bevat de structuur ertussen, hexadecimaal. Voeg",
        "de twee reeksen samen tot covered.bin, decodeer de structuur naar signature.der,",
        "en voer uit:",
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Um documento assinado, e como foi assinado",
    covers=(
        "Este ficheiro leva uma assinatura digital. Cobre cada byte do ficheiro",
        "exceto o lugar onde está escrita: um byte mudado em qualquer sítio parte-a, e",
        "o programa de leitura di-lo.",
    ),
    proves=(
        "O certificado é de demonstração: foi feito para este exemplo,",
        "e não nomeia nenhuma pessoa nem empresa. A assinatura prova que o ficheiro",
        "não mudou; não prova nada sobre quem o assinou, porque ninguém",
        "responde por este certificado.",
    ),
    reason="Mostra como se assina um documento",
    signed_label="Assinado",
    made_heading="Como foi assinado",
    made_key="1. A chave e o seu certificado foram feitos uma vez, a partir da raiz do repositório:",
    made_certificate="2. A biblioteca recebe o certificado em DER, que este comando escreve:",
    made_signature=(
        "3. A biblioteca deixa espaço no ficheiro para a assinatura, calcula o resumo",
        "de cada byte à volta e passa ao programa os atributos a assinar.",
        "A chave assina-os, e nunca chega à biblioteca:",
    ),
    made_structure=(
        "4. A biblioteca embrulha essa assinatura e o certificado na estrutura",
        "que uma assinatura PAdES leva, e escreve-a no espaço que deixou.",
    ),
    check_heading="Verificá-la sem esta biblioteca",
    check=(
        "O /ByteRange do ficheiro nomeia os dois troços de bytes que a assinatura cobre,",
        "e /Contents guarda a estrutura entre eles, em hexadecimal. Junte",
        "os dois troços em covered.bin, descodifique a estrutura em signature.der,",
        "e execute:",
    ),
)

# The page in Italian.
ITALIAN = Words(
    title="Un documento firmato, e come è stato firmato",
    covers=(
        "Questo file porta una firma digitale. Copre ogni byte del file",
        "tranne il punto in cui è scritta: un byte cambiato ovunque la rompe, e",
        "il programma di lettura lo dice.",
    ),
    proves=(
        "Il certificato è di dimostrazione: è stato fatto per questo esempio,",
        "e non nomina nessuna persona né azienda. La firma prova che il file",
        "non è cambiato; non prova nulla su chi l’ha firmato, perché nessuno",
        "garantisce per questo certificato.",
    ),
    reason="Mostra come si firma un documento",
    signed_label="Firmato",
    made_heading="Come è stato firmato",
    made_key="1. La chiave e il suo certificato sono stati fatti una volta, dalla radice del repository:",
    made_certificate="2. La libreria riceve il certificato in DER, che scrive questo:",
    made_signature=(
        "3. La libreria lascia spazio nel file per la firma, calcola l’impronta",
        "di ogni byte intorno e passa al programma gli attributi da firmare.",
        "La chiave li firma, e non arriva mai alla libreria:",
    ),
    made_structure=(
        "4. La libreria avvolge quella firma e il certificato nella struttura",
        "che porta una firma PAdES, e la scrive nello spazio lasciato.",
    ),
    check_heading="Verificarla senza questa libreria",
    check=(
        "Il /ByteRange del file nomina i due tratti di byte che la firma copre,",
        "e /Contents tiene la struttura tra di essi, in esadecimale. Unite",
        "i due tratti in covered.bin, decodificate la struttura in signature.der,",
        "ed eseguite:",
    ),
)

# The page in Spanish.
SPANISH = Words(
    title="Un documento firmado, y cómo se firmó",
    covers=(
        "Este archivo lleva una firma digital. Cubre cada byte del archivo",
        "salvo el lugar donde está escrita: un byte cambiado en cualquier sitio la rompe, y",
        "el programa de lectura lo dice.",
    ),
    proves=(
        "El certificado es de demostración: se hizo para este ejemplo,",
        "y no nombra a ninguna persona ni empresa. La firma prueba que el archivo",
        "no ha cambiado; no prueba nada de quién lo firmó, porque nadie",
        "responde de este certificado.",
    ),
    reason="Muestra cómo se firma un documento",
    signed_label="Firmado",
    made_heading="Cómo se firmó",
    made_key="1. La clave y su certificado se hicieron una vez, desde la raíz del repositorio:",
    made_certificate="2. La biblioteca recibe el certificado en DER, que escribe esto:",
    made_signature=(
        "3. La biblioteca deja sitio en el archivo para la firma, calcula el resumen",
        "de cada byte a su alrededor y pasa al programa los atributos que firmar.",
        "La clave los firma, y nunca llega a la biblioteca:",
    ),
    made_structure=(
        "4. La biblioteca envuelve esa firma y el certificado en la estructura",
        "que lleva una firma PAdES, y la escribe en el sitio que dejó.",
    ),
    check_heading="Comprobarla sin esta biblioteca",
    check=(
        "El /ByteRange del archivo nombra los dos tramos de bytes que cubre la firma,",
        "y /Contents guarda la estructura entre ellos, en hexadecimal. Concatene",
        "los dos tramos en covered.bin, decodifique la estructura en signature.der,",
        "y ejecute:",
    ),
)

# The page in German.
GERMAN = Words(
    title="Ein signiertes Dokument und seine Signatur",
    covers=(
        "Diese Datei trägt eine digitale Signatur. Sie deckt jedes Byte ab,",
        "außer der Stelle, an der sie steht: Ein geändertes Byte irgendwo bricht sie,",
        "und die Lesesoftware sagt es.",
    ),
    proves=(
        "Das Zertifikat ist ein Vorführzertifikat, für dieses Beispiel erstellt,",
        "und nennt weder Person noch Firma. Die Signatur beweist, dass die Datei",
        "unverändert ist; über den Unterzeichner beweist sie nichts, denn niemand",
        "bürgt für dieses Zertifikat.",
    ),
    reason="Zeigt, wie ein Dokument signiert wird",
    signed_label="Signiert",
    made_heading="Wie es signiert wurde",
    made_key="1. Schlüssel und Zertifikat, einmal im Wurzelordner des Repositorys erstellt:",
    made_certificate="2. Die Bibliothek erhält das Zertifikat als DER, geschrieben so:",
    made_signature=(
        "3. Die Bibliothek lässt Platz für die Signatur, bildet den Hashwert",
        "aller Bytes ringsum und übergibt dem Programm die zu signierenden Attribute.",
        "Der Schlüssel signiert sie und erreicht die Bibliothek nie:",
    ),
    made_structure=(
        "4. Die Bibliothek verpackt diese Signatur und das Zertifikat in die Struktur",
        "einer PAdES-Signatur und schreibt sie in den freigelassenen Platz.",
    ),
    check_heading="Prüfung ohne diese Bibliothek",
    check=(
        "/ByteRange nennt die zwei Bytefolgen, die die Signatur abdeckt,",
        "und /Contents enthält die Struktur dazwischen, hexadezimal. Die beiden Folgen",
        "zu covered.bin zusammenfügen, die Struktur zu signature.der dekodieren",
        "und ausführen:",
    ),
)

# 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 size_of(kind: str) -> float:
    """The size a line of `kind` is set at, in points."""
    if kind == HEADING:
        return HEADING_SIZE
    if kind == SECTION:
        return SECTION_SIZE
    if kind == COMMAND:
        return COMMAND_SIZE
    return BODY_SIZE


def drop_after(kind: str, before: str) -> float:
    """How far a line of `kind` sits below the line before it, of kind `before`."""
    if before == HEADING:
        return 32.0
    if before == BODY and kind == SECTION:
        return PAST_THE_BOX
    if kind == SECTION:
        return 30.0
    if kind == PARAGRAPH or before == SECTION:
        return 22.0
    if before == COMMAND and kind == COMMAND:
        return 12.0
    if kind == COMMAND:
        return 14.0
    if before == COMMAND:
        return 19.0
    return 15.0


def carried(lines: tuple[str, ...], first: str, rest: str) -> list[tuple[str, str]]:
    """The lines of one block, the first of kind `first` and the others of kind `rest`."""
    return [(line, first if index == 0 else rest) for index, line in enumerate(lines)]


def lines(words: Words) -> list[tuple[str, str]]:
    """Every line the page draws, in the order they are drawn, with its kind."""
    return [
        (words.title, HEADING),
        *((line, BODY) for line in words.covers),
        *carried(words.proves, PARAGRAPH, BODY),
        (words.made_heading, SECTION),
        (words.made_key, STEP),
        *((line, COMMAND) for line in KEY_COMMAND),
        (words.made_certificate, STEP),
        (" ".join(CERTIFICATE_COMMAND), COMMAND),
        *carried(words.made_signature, STEP, STEP_CARRIED_ON),
        (" ".join(SIGN_COMMAND), COMMAND),
        *carried(words.made_structure, STEP, STEP_CARRIED_ON),
        (words.check_heading, SECTION),
        *carried(words.check, STEP, STEP_CARRIED_ON),
        *((line, COMMAND) for line in CHECK_COMMAND),
    ]


def drawing(words: Words) -> list[tuple[str, float, float]]:
    """Every line the page draws, in the order they are drawn.

    Each is what it says, the size it is set at, and where its baseline sits in points
    up from the foot of the sheet.
    """
    drawn = []
    baseline = HEADING_BASELINE
    before = None
    for line, kind in lines(words):
        if before is not None:
            baseline -= drop_after(kind, before)
        drawn.append((line, size_of(kind), baseline))
        before = kind
    return drawn


# How far across the seal is drawn, in points.
SEAL = 40.0


def seal() -> hqf_pdf.Drawing:
    """The seal laid under the lines of the signature box: two rings."""
    content = hqf_pdf.Content()
    content.set_stroke(hqf_pdf.Rgb(0.12, 0.28, 0.52))
    content.set_line_width(1.5)
    content.circle(SEAL / 2.0, SEAL / 2.0, SEAL / 2.0 - 2.0)
    content.stroke()
    content.set_line_width(0.8)
    content.circle(SEAL / 2.0, SEAL / 2.0, SEAL / 2.0 - 7.0)
    content.stroke()
    return hqf_pdf.Drawing(content, hqf_pdf.Rect(0.0, 0.0, SEAL, SEAL))


def signature_box(
    handle: hqf_pdf.FontHandle, sealed: hqf_pdf.DrawingHandle, words: Words
) -> hqf_pdf.SignatureField:
    """The signature box: a framed field that shows, once signed, who signed it and
    when, set flush right over the seal, which sits at the left of the box."""
    x, y, width, height = BOX
    shown = hqf_pdf.SignatureAppearance(
        handle,
        BOX_SIZE,
        lines=[SIGNER, f"{words.signed_label} {SIGNED_AT_SHOWN}"],
        align=hqf_pdf.FieldAlign.Right,
        drawing=sealed,
        fit=hqf_pdf.IconFit(leftover=(0.0, 0.5)),
    )
    return hqf_pdf.SignatureField(
        FIELD,
        x,
        y,
        width,
        height,
        border_color=BORDER,
        border_width=BORDER_WIDTH,
        appearance=shown,
    )


def document(words: Words, face: Path) -> hqf_pdf.Document:
    """The document and its one page, before it is signed."""
    result = hqf_pdf.Document()
    result.set_license(_licence.licensed())
    result.set_info("Title", words.title)
    handle = result.add_font(hqf_pdf.Font.from_path(face))

    content = hqf_pdf.Content()
    for line, size, baseline in drawing(words):
        content.draw_text(handle, size, LEFT, baseline, line)
    page = hqf_pdf.Page.a4()
    page.set_content(content)
    sealed = result.add_drawing(seal())
    page.add_signature(signature_box(handle, sealed, words))
    result.add_page(page)
    return result


def signature(words: Words) -> hqf_pdf.Signature:
    """What the signature states about itself."""
    return hqf_pdf.Signature(
        FIELD,
        name=SIGNER,
        reason=words.reason,
        signed_at=SIGNED_AT,
        sub_filter=hqf_pdf.SubFilter.EtsiCadesDetached,
    )


def signed(words: Words, face: Path) -> bytes:
    """The document signed with the demonstration key, through `openssl`."""
    signer = _signer.demonstration()
    return document(words, face).to_signed_bytes(signature(words), signer)


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 = Path(_out.output_path(Path(_language.file_name("signed.pdf", language)).stem))

    pdf = signed(words, _out.font_path())
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_bytes(pdf)
    print(f"wrote {out} ({len(pdf)} bytes)")


if __name__ == "__main__":
    main()
