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

import subprocess
from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

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",
)

# The command that writes the certificate as DER, run from the repository's root.
CERTIFICATE_COMMAND = (
    "openssl",
    "x509",
    "-in",
    "keys/demonstration_signer.crt",
    "-outform",
    "DER",
)

# The command that signs what it reads on its standard input with the demonstration key,
# run from the repository's root.
SIGN_COMMAND = ("openssl", "dgst", "-sha256", "-sign", "keys/demonstration_signer.key")

# The command that checks the signature without this library, as the page sets it over
# two lines.
CHECK_COMMAND = (
    "openssl cms -verify -binary -inform DER -in signature.der -content covered.bin",
    "    -CAfile keys/demonstration_signer.crt -purpose any",
)

# The name the certificate carries, which the signature states and the box on the page
# shows.
SIGNER = "hqf-pdf demonstration signer"

# 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 porte une signature numérique. Elle couvre chaque octet du",
        "fichier sauf la place où elle est écrite : un seul octet changé, où que",
        "ce soit, la rompt, et le logiciel de lecture le dit.",
    ),
    proves=(
        "Le certificat est un certificat de démonstration : il a été fait pour",
        "cet exemple, et il ne nomme ni personne ni entreprise. La signature",
        "prouve que le fichier n'a pas changé ; elle ne prouve rien de qui l'a",
        "signé, 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é faits une fois, depuis la racine du dépôt :",
    made_certificate="2. La bibliothèque reçoit le certificat en DER, que ceci écrit :",
    made_signature=(
        "3. La bibliothèque laisse dans le fichier la place de la signature, calcule",
        "l'empreinte de chaque octet autour, et donne au programme les attributs à",
        "signer. La clé les signe, et n'entre jamais dans la bibliothèque :",
    ),
    made_structure=(
        "4. La bibliothèque enveloppe cette signature et le certificat dans la",
        "structure qu'une signature PAdES porte, et l'écrit dans la place laissée.",
    ),
    check_heading="Le vérifier sans cette bibliothèque",
    check=(
        "Le /ByteRange du fichier nomme les deux plages d'octets que la signature",
        "couvre, et /Contents contient la structure entre elles, en hexadécimal.",
        "Joignez les deux plages dans covered.bin, décodez la structure dans",
        "signature.der, puis lancez :",
    ),
)

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


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


def signature_box(handle: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.SignatureField:
    """The signature box: a framed field that shows, once signed, who signed it and when."""
    x, y, width, height = BOX
    shown = hqf_pdf.SignatureAppearance(
        handle, BOX_SIZE, lines=[SIGNER, f"{words.signed_label} {SIGNED_AT_SHOWN}"]
    )
    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)
    page.add_signature(signature_box(handle, 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 run(arguments: tuple[str, ...], given: bytes) -> bytes:
    """Runs the command `arguments` names from the repository's root.

    It is handed `given` on its standard input, and what it writes on its standard
    output comes back. A command that fails raises `subprocess.CalledProcessError`.
    """
    return subprocess.run(
        arguments, input=given, capture_output=True, check=True, cwd=_out.ROOT
    ).stdout


def signed(words: Words, face: Path) -> bytes:
    """The document signed with the demonstration key, through `openssl`."""
    certificate = run(CERTIFICATE_COMMAND, b"")
    signer = hqf_pdf.CadesSigner(
        [certificate], lambda attributes: run(SIGN_COMMAND, attributes)
    )
    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()
