"""Writes one document twice — spelled out, then packed into object streams —
and creates a page stating what each of them weighs.

The Python twin of the `write_object_streams` example in Rust. A PDF is mostly
dictionaries: the catalogue, the page tree, every page, every font, every
annotation. None of them is a stream, so none of them is compressed, and each is
written out in full. Object streams gather them into streams that compress
together, and the table saying where everything is becomes a stream as well.

The document being weighed is built here and written both ways. The page that
reports the two weights is itself written packed, so the file this leaves behind
is one of the two things it is talking about.

The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which set
is drawn. The numbers are not language: they are counted off the two files.

A second page weighs the same document other ways: with compression off and at three
levels of it, with and without an information dictionary, through a dry run that writes
nothing, and written with its warnings reported. It says what the document is set to,
what a cover put in front and a bookmark put first make of it, and what a line measured
inside a measuring pass costs the file.

A second path, if one is given, is where the document that was weighed is written
spelled out, so that the two spellings of one document can be handed to reading software
side by side.

Usage: python examples/write_object_streams.py [out.pdf] [spelled_out.pdf]
       HQF_PDF_LANG=fr python examples/write_object_streams.py
"""

from __future__ import annotations

import io
import sys
from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# Where the committed fonts sit.
FONT_DIR = _out.ROOT / "crates" / "hqf-pdf" / "tests" / "fonts"

# How many pages the document being weighed holds.
#
# Every page is a dictionary, and so is everything hanging off it, which is exactly what
# packing gathers up: a document of one page would show almost nothing.
WEIGHED_PAGES = 24


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

    What is not language stays out of it: the three weights are counted off the files
    themselves.
    """

    # The line across the top of the page.
    title: str
    # What packing does, in two sentences.
    why: str
    # The heading over the three weights.
    weights: str
    # What the document being weighed is, cut where the page count goes in.
    subject_before: str
    subject_after: str
    # The label on the weight of the document spelled out.
    flat: str
    # The label on the weight of the same document packed.
    packed: str
    # The label on what was saved.
    saved: str
    # What a weight is counted in.
    unit: str
    # The closing note, cut where the share saved goes into it.
    note_before: str
    note_after: str
    # The line saying what this very file is.
    itself: str
    # The second page's heading.
    other_ways: str
    # The weights at each compression; `{off}`, `{fastest}`, `{default}`, `{smallest}`
    # and the three `{level_…}` stand for them.
    levels: str
    # The weights with and without an information dictionary; `{with}`, `{without}` and
    # `{written}` stand for them.
    information: str
    # What a dry run says; `{pages}`, `{objects}`, `{version}`, `{required}` and
    # `{warnings}` stand for them.
    dry_run: str
    # What writing with the warnings reported gives; `{bytes}`, `{streamed}` and
    # `{warnings}` stand for them.
    reporting: str
    # What the document is set to; `{packed}`, `{linearized}` and `{required}` stand for
    # them.
    settings: str
    # What a cover and a bookmark put first make of it; `{pages}` and `{bookmark}` stand
    # for them.
    inserted: str
    # The title of the cover put in front.
    cover: str
    # What a line measured inside a measuring pass costs; `{inside}`, `{held}` and
    # `{outside}` stand for the three weights.
    measured: str
    # Yes, then no.
    yes_no: tuple[str, str]

    def subject(self) -> str:
        """What the document being weighed is."""
        return f"{self.subject_before}{WEIGHED_PAGES}{self.subject_after}"

    def note(self, share: int) -> str:
        """The closing note, with the share saved in it."""
        return f"{self.note_before}{share}{self.note_after}"


# The page in English.
ENGLISH = Words(
    title="What packing a document saves",
    why=(
        "A PDF is mostly dictionaries — the catalogue, the page tree, every page, "
        "every font, every annotation — and a dictionary is not a stream, so each one "
        "is written out in full and none of them is compressed.\nObject streams gather "
        "them into streams that are compressed together, and the table stating where "
        "every object lives becomes a stream too. The document a reader sees is the "
        "same one either way."
    ),
    weights="The same document, weighed twice",
    subject_before="The document weighed here holds ",
    subject_after=" pages of text, each with a heading of its own.",
    flat="Spelled out",
    packed="Packed",
    saved="Saved",
    unit="bytes",
    note_before="Packing this document saved ",
    note_after=(
        " per cent of it. What it saves goes up with the number of pages, because a "
        "page costs a handful of dictionaries and dictionaries are what packing "
        "compresses."
    ),
    itself=(
        "This very file is packed, so a reader that opened it has read one of the two "
        "documents being weighed."
    ),
    other_ways="The same document, weighed other ways",
    levels=(
        "With compression off it weighs {off} bytes; at level {level_fastest}, "
        "{fastest}; at level {level_default}, the default, {default}; at level "
        "{level_smallest}, {smallest}."
    ),
    information=(
        "Given a title, it weighs {with} bytes with its information dictionary and "
        "{without} without it, the title then said in its metadata alone; the "
        "dictionary is written: {written}."
    ),
    dry_run=(
        "A dry run, which writes nothing, counts {pages} pages and {objects} objects, "
        "written as PDF {version} though PDF {required} would do, and {warnings} "
        "warnings."
    ),
    reporting=(
        "Written with its warnings reported it weighs {bytes} bytes, and {streamed} "
        "written to a stream the same way; warnings: {warnings}."
    ),
    settings=(
        "Packed into object streams: {packed}; laid out first page first: "
        "{linearized}; the version it needs: PDF {required}."
    ),
    inserted=(
        "With a cover put in front and a bookmark to it put first, it holds {pages} "
        "pages, and its first bookmark reads “{bookmark}”."
    ),
    cover="Cover",
    measured=(
        "A line of four hundred characters measured inside a measuring pass costs the "
        "file nothing: {inside} bytes, and {held} with the pass held open by hand, "
        "against {outside} when measured outside one."
    ),
    yes_no=(
        "yes",
        "no",
    ),
)

# The page in French.
FRENCH = Words(
    title="Ce que le compactage d’un document fait gagner",
    why=(
        "Un PDF est surtout fait de dictionnaires — le catalogue, l’arbre des pages, "
        "chaque page, chaque police, chaque annotation — et un dictionnaire n’est pas "
        "un flux : chacun est donc écrit en toutes lettres, et aucun n’est "
        "compressé.\nLes flux d’objets les rassemblent dans des flux compressés "
        "ensemble, et la table qui dit où se trouve chaque objet devient elle aussi un "
        "flux. Le document que le lecteur voit est le même dans les deux cas."
    ),
    weights="Le même document, pesé deux fois",
    subject_before="Le document pesé ici tient en ",
    subject_after=" pages de texte, chacune avec son propre titre.",
    flat="En toutes lettres",
    packed="Compacté",
    saved="Gagné",
    unit="octets",
    note_before="Compacter ce document en a fait gagner ",
    note_after=(
        " pour cent. Le gain croît avec le nombre de pages, car une page coûte une "
        "poignée de dictionnaires, et ce sont les dictionnaires que le compactage "
        "compresse."
    ),
    itself=(
        "Ce fichier-ci est compacté : un lecteur qui l’a ouvert a donc lu l’un des "
        "deux documents pesés."
    ),
    other_ways="Le même document, pesé autrement",
    levels=(
        "Sans compression, il pèse {off} octets ; au niveau {level_fastest}, "
        "{fastest} ; au niveau {level_default}, celui par défaut, {default} ; au "
        "niveau {level_smallest}, {smallest}."
    ),
    information=(
        "Doté d’un titre, il pèse {with} octets avec son dictionnaire d’informations et "
        "{without} sans lui, le titre n’étant alors indiqué que dans ses métadonnées ; "
        "le dictionnaire est écrit : {written}."
    ),
    dry_run=(
        "Un essai à blanc, qui n’écrit rien, compte {pages} pages et {objects} objets, "
        "écrits en PDF {version} alors que le PDF {required} suffirait, et "
        "{warnings} avertissements."
    ),
    reporting=(
        "Écrit en signalant ses avertissements, il pèse {bytes} octets, et {streamed} "
        "écrit de même dans un flux ; avertissements : {warnings}."
    ),
    settings=(
        "Compacté en flux d’objets : {packed} ; ordonné pour afficher la première page "
        "d’abord : {linearized} ; version nécessaire : PDF {required}."
    ),
    inserted=(
        "Avec une couverture placée devant et un signet vers elle placé en tête, il "
        "compte {pages} pages, et son premier signet s’intitule « {bookmark} »."
    ),
    cover="Couverture",
    measured=(
        "Une ligne de quatre cents caractères mesurée pendant une passe de mesure ne "
        "coûte rien au fichier : {inside} octets, et {held} avec la passe tenue "
        "ouverte à la main, contre {outside} quand elle est mesurée hors passe."
    ),
    yes_no=(
        "oui",
        "non",
    ),
)

# The page in Dutch.
DUTCH = Words(
    title="Wat het inpakken van een document bespaart",
    why=(
        "Een pdf bestaat vooral uit woordenboeken (de catalogus, de paginaboom, elke "
        "pagina, elk lettertype, elke annotatie), en een woordenboek is geen stroom, "
        "dus elk wordt voluit geschreven en geen enkel wordt "
        "gecomprimeerd.\nObjectstromen verzamelen ze in stromen die samen "
        "gecomprimeerd worden, en de tabel die zegt waar elk object staat, wordt ook "
        "een stroom. Het document dat een lezer ziet is in beide gevallen hetzelfde."
    ),
    weights="Hetzelfde document, twee keer gewogen",
    subject_before="Het hier gewogen document bevat",
    subject_after=" pagina’s tekst, elk met een eigen kop.",
    flat="Voluit",
    packed="Ingepakt",
    saved="Bespaard",
    unit="bytes",
    note_before="Het inpakken van dit document bespaarde",
    note_after=(
        " procent ervan. Wat het bespaart, stijgt met het aantal pagina’s, omdat een "
        "pagina een handvol woordenboeken kost en woordenboeken zijn wat inpakken "
        "comprimeert."
    ),
    itself=(
        "Dit bestand zelf is ingepakt, dus wie het opende, heeft een van de twee "
        "gewogen documenten gelezen."
    ),
    other_ways="Hetzelfde document, op andere manieren gewogen",
    levels=(
        "Zonder compressie weegt het {off} bytes; op niveau {level_fastest}, "
        "{fastest}; op niveau {level_default}, de standaard, {default}; op niveau "
        "{level_smallest}, {smallest}."
    ),
    information=(
        "Met een titel weegt het {with} bytes met zijn informatiewoordenboek en "
        "{without} zonder, de titel dan alleen in de metadata; het woordenboek wordt "
        "geschreven: {written}."
    ),
    dry_run=(
        "Een proefrun, die niets schrijft, telt {pages} pagina’s en {objects} "
        "objecten, geschreven als PDF {version} terwijl PDF {required} zou volstaan, "
        "en {warnings} waarschuwingen."
    ),
    reporting=(
        "Geschreven met melding van de waarschuwingen, weegt het {bytes} bytes, en "
        "{streamed} op dezelfde manier naar een stroom geschreven; waarschuwingen: "
        "{warnings}."
    ),
    settings=(
        "Ingepakt in objectstromen: {packed}; met de eerste pagina eerst: "
        "{linearized}; de versie die het nodig heeft: PDF {required}."
    ),
    inserted=(
        "Met een omslag ervoor en een bladwijzer ernaar als eerste, bevat het {pages} "
        "pagina’s, en zijn eerste bladwijzer luidt „{bookmark}”."
    ),
    cover="Omslag",
    measured=(
        "Een regel van vierhonderd tekens gemeten binnen een meetronde kost het "
        "bestand niets: {inside} bytes, en {held} met de ronde met de hand "
        "opengehouden, tegen {outside} gemeten buiten een ronde."
    ),
    yes_no=(
        "ja",
        "nee",
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="O que se poupa ao empacotar um documento",
    why=(
        "Um PDF é sobretudo dicionários (o catálogo, a árvore de páginas, cada "
        "página, cada tipo de letra, cada anotação) e um dicionário não é um fluxo, "
        "por isso cada um é escrito por extenso e nenhum é comprimido.\nOs fluxos de "
        "objetos agrupam-nos e comprimem-nos em conjunto, e a tabela que diz onde "
        "vive cada objeto também passa a ser um fluxo. O documento que o leitor vê é "
        "o mesmo nos dois casos."
    ),
    weights="O mesmo documento, pesado duas vezes",
    subject_before="O documento pesado aqui tem",
    subject_after=" páginas de texto, cada uma com o seu título.",
    flat="Por extenso",
    packed="Empacotado",
    saved="Poupado",
    unit="bytes",
    note_before="Empacotar este documento poupou",
    note_after=(
        " por cento dele. O que se poupa cresce com o número de páginas, porque uma "
        "página custa uns quantos dicionários e os dicionários são o que o "
        "empacotamento comprime."
    ),
    itself=(
        "Este mesmo ficheiro está empacotado, por isso quem o abriu leu um dos dois "
        "documentos pesados."
    ),
    other_ways="O mesmo documento, pesado de outras formas",
    levels=(
        "Sem compressão pesa {off} bytes; no nível {level_fastest}, {fastest}; no "
        "nível {level_default}, o predefinido, {default}; no nível {level_smallest}, "
        "{smallest}."
    ),
    information=(
        "Com um título, pesa {with} bytes com o seu dicionário de informação e "
        "{without} sem ele, ficando então o título só nos metadados; o dicionário é "
        "escrito: {written}."
    ),
    dry_run=(
        "Uma simulação, que não escreve nada, conta {pages} páginas e {objects} "
        "objetos, escritos como PDF {version} embora bastasse PDF {required}, e "
        "{warnings} avisos."
    ),
    reporting=(
        "Escrito com os avisos comunicados pesa {bytes} bytes, e {streamed} escrito "
        "da mesma forma num fluxo; avisos: {warnings}."
    ),
    settings=(
        "Empacotado em fluxos de objetos: {packed}; com a primeira página primeiro: "
        "{linearized}; a versão de que precisa: PDF {required}."
    ),
    inserted=(
        "Com uma capa à frente e um marcador para ela posto em primeiro, tem {pages} "
        "páginas, e o seu primeiro marcador diz «{bookmark}»."
    ),
    cover="Capa",
    measured=(
        "Uma linha de quatrocentos caracteres medida dentro de uma passagem de "
        "medição não custa nada ao ficheiro: {inside} bytes, e {held} com a passagem "
        "mantida aberta à mão, contra {outside} quando medida fora de uma."
    ),
    yes_no=(
        "sim",
        "não",
    ),
)

# The page in Italian.
ITALIAN = Words(
    title="Cosa fa risparmiare impacchettare un documento",
    why=(
        "Un PDF è soprattutto dizionari (il catalogo, l’albero delle pagine, ogni "
        "pagina, ogni font, ogni annotazione) e un dizionario non è un flusso, così "
        "ciascuno è scritto per intero e nessuno è compresso.\nI flussi di oggetti li "
        "raccolgono in flussi compressi insieme, e anche la tabella che dice dove "
        "vive ogni oggetto diventa un flusso. Il documento che il lettore vede è lo "
        "stesso nei due casi."
    ),
    weights="Lo stesso documento, pesato due volte",
    subject_before="Il documento pesato qui contiene",
    subject_after=" pagine di testo, ciascuna con il suo titolo.",
    flat="Per esteso",
    packed="Impacchettato",
    saved="Risparmiato",
    unit="byte",
    note_before="Impacchettare questo documento ha fatto risparmiare il",
    note_after=(
        " per cento. Il risparmio cresce con il numero di pagine, perché una pagina "
        "costa qualche dizionario e i dizionari sono ciò che l’impacchettamento "
        "comprime."
    ),
    itself=(
        "Questo file stesso è impacchettato, così chi lo ha aperto ha letto uno dei "
        "due documenti pesati."
    ),
    other_ways="Lo stesso documento, pesato in altri modi",
    levels=(
        "Senza compressione pesa {off} byte; al livello {level_fastest}, {fastest}; "
        "al livello {level_default}, quello predefinito, {default}; al livello "
        "{level_smallest}, {smallest}."
    ),
    information=(
        "Con un titolo, pesa {with} byte con il suo dizionario di informazioni e "
        "{without} senza, il titolo detto allora solo nei metadati; il dizionario è "
        "scritto: {written}."
    ),
    dry_run=(
        "Una prova a vuoto, che non scrive nulla, conta {pages} pagine e {objects} "
        "oggetti, scritti come PDF {version} anche se basterebbe PDF {required}, e "
        "{warnings} avvisi."
    ),
    reporting=(
        "Scritto con i suoi avvisi segnalati pesa {bytes} byte, e {streamed} scritto "
        "allo stesso modo in un flusso; avvisi: {warnings}."
    ),
    settings=(
        "Impacchettato in flussi di oggetti: {packed}; con la prima pagina in testa: "
        "{linearized}; la versione che richiede: PDF {required}."
    ),
    inserted=(
        "Con una copertina davanti e un segnalibro verso di essa messo per primo, ha "
        "{pages} pagine, e il suo primo segnalibro dice «{bookmark}»."
    ),
    cover="Copertina",
    measured=(
        "Una riga di quattrocento caratteri misurata dentro una passata di misura non "
        "costa nulla al file: {inside} byte, e {held} con la passata tenuta aperta a "
        "mano, contro {outside} se misurata fuori."
    ),
    yes_no=(
        "sì",
        "no",
    ),
)

# The page in Spanish.
SPANISH = Words(
    title="Lo que ahorra empaquetar un documento",
    why=(
        "Un PDF es sobre todo diccionarios —el catálogo, el árbol de páginas, cada "
        "página, cada fuente, cada anotación— y un diccionario no es un flujo, así "
        "que cada uno se escribe entero y ninguno se comprime.\nLos flujos de objetos "
        "los reúnen en flujos que se comprimen juntos, y la tabla que dice dónde está "
        "cada objeto se vuelve también un flujo. El documento que ve el lector es el "
        "mismo en los dos casos."
    ),
    weights="El mismo documento, pesado dos veces",
    subject_before="El documento pesado aquí tiene ",
    subject_after=" páginas de texto, cada una con su título.",
    flat="Sin empaquetar",
    packed="Empaquetado",
    saved="Ahorrado",
    unit="bytes",
    note_before="Empaquetar este documento ahorró el ",
    note_after=(
        " por ciento. Lo que ahorra crece con el número de páginas, porque una página "
        "cuesta unos cuantos diccionarios y los diccionarios son lo que comprime el "
        "empaquetado."
    ),
    itself=(
        "Este mismo archivo está empaquetado, así que quien lo haya abierto ha leído "
        "uno de los dos documentos pesados."
    ),
    other_ways="El mismo documento, pesado de otras formas",
    levels=(
        "Sin compresión pesa {off} bytes; al nivel {level_fastest}, {fastest}; al "
        "nivel {level_default}, el de por defecto, {default}; al nivel "
        "{level_smallest}, {smallest}."
    ),
    information=(
        "Con un título, pesa {with} bytes con su diccionario de información y "
        "{without} sin él, cuando el título figura solo en sus metadatos; el "
        "diccionario se escribe: {written}."
    ),
    dry_run=(
        "Una simulación, que no escribe nada, cuenta {pages} páginas y {objects} "
        "objetos, escritos como PDF {version} aunque bastaría PDF {required}, y "
        "{warnings} avisos."
    ),
    reporting=(
        "Escrito con sus avisos notificados pesa {bytes} bytes, y {streamed} escrito "
        "igual en un flujo; avisos: {warnings}."
    ),
    settings=(
        "Empaquetado en flujos de objetos: {packed}; con la primera página primero: "
        "{linearized}; la versión que necesita: PDF {required}."
    ),
    inserted=(
        "Con una portada delante y un marcador hacia ella puesto primero, tiene "
        "{pages} páginas, y su primer marcador dice «{bookmark}»."
    ),
    cover="Portada",
    measured=(
        "Una línea de cuatrocientos caracteres medida dentro de una pasada de medida "
        "no le cuesta nada al archivo: {inside} bytes, y {held} con la pasada "
        "mantenida abierta a mano, frente a {outside} si se mide fuera de una."
    ),
    yes_no=(
        "sí",
        "no",
    ),
)

# The page in German.
GERMAN = Words(
    title="Was das Packen eines Dokuments spart",
    why=(
        "Ein PDF besteht größtenteils aus Wörterbüchern — dem Katalog, dem "
        "Seitenbaum, jeder Seite, jeder Schrift, jeder Anmerkung —, und ein "
        "Wörterbuch ist kein Datenstrom, also wird jedes vollständig ausgeschrieben "
        "und keines komprimiert.\nObjektströme sammeln sie in Datenströme, die "
        "gemeinsam komprimiert werden, und auch die Tabelle, die sagt, wo jedes "
        "Objekt liegt, wird zu einem Datenstrom. Das Dokument, das ein Leser sieht, "
        "ist in beiden Fällen dasselbe."
    ),
    weights="Dasselbe Dokument, zweimal gewogen",
    subject_before="Das hier gewogene Dokument enthält ",
    subject_after=" Seiten Text, jede mit einer eigenen Überschrift.",
    flat="Ausgeschrieben",
    packed="Gepackt",
    saved="Gespart",
    unit="Bytes",
    note_before="Das Packen hat bei diesem Dokument ",
    note_after=(
        " Prozent gespart. Die Ersparnis wächst mit der Seitenzahl, weil eine Seite "
        "eine Handvoll Wörterbücher kostet und Wörterbücher das sind, was das Packen "
        "komprimiert."
    ),
    itself=(
        "Genau diese Datei ist gepackt, also hat ein Leser, der sie geöffnet hat, "
        "eines der beiden gewogenen Dokumente gelesen."
    ),
    other_ways="Dasselbe Dokument, anders gewogen",
    levels=(
        "Ohne Komprimierung wiegt es {off} Bytes; auf Stufe {level_fastest} "
        "{fastest}; auf Stufe {level_default}, der Voreinstellung, {default}; auf "
        "Stufe {level_smallest} {smallest}."
    ),
    information=(
        "Mit einem Titel wiegt es {with} Bytes mit seinem Informationswörterbuch und "
        "{without} ohne, der Titel dann allein in seinen Metadaten; das Wörterbuch "
        "wird geschrieben: {written}."
    ),
    dry_run=(
        "Ein Probelauf, der nichts schreibt, zählt {pages} Seiten und {objects} "
        "Objekte, als PDF {version} geschrieben, obwohl PDF {required} genügen würde, "
        "und {warnings} Warnungen."
    ),
    reporting=(
        "Mit gemeldeten Warnungen geschrieben wiegt es {bytes} Bytes, und {streamed}, "
        "wenn es ebenso in einen Datenstrom geschrieben wird; Warnungen: {warnings}."
    ),
    settings=(
        "In Objektströme gepackt: {packed}; mit der ersten Seite zuerst angelegt: "
        "{linearized}; die nötige Version: PDF {required}."
    ),
    inserted=(
        "Mit einem vorangestellten Deckblatt und einem Lesezeichen darauf an erster "
        "Stelle hat es {pages} Seiten, und sein erstes Lesezeichen lautet "
        "„{bookmark}“."
    ),
    cover="Deckblatt",
    measured=(
        "Eine Zeile von vierhundert Zeichen, innerhalb eines Messdurchgangs gemessen, "
        "kostet die Datei nichts: {inside} Bytes, und {held}, wenn der Durchgang von "
        "Hand offen gehalten wird, gegenüber {outside}, wenn außerhalb gemessen."
    ),
    yes_no=(
        "ja",
        "nein",
    ),
)

# 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 of everything on the page.
X = 60.0

# The width every block is broken to.
ROOM = 475.0

# The baseline the title sits on.
TITLE_TOP = 780.0

# The top of the block that says what packing does.
WHY_TOP = 748.0

# The top of the line naming what was weighed.
SUBJECT_TOP = 636.0

# The top of the heading over the three weights.
WEIGHTS_TOP = 600.0

# The top of the first of the three weights.
FIRST_WEIGHT_TOP = 574.0

# How far apart two weights sit.
WEIGHT_DROP = 20.0

# Where the number of a weight begins, its label sitting at X.
NUMBER_X = X + 160.0

# The top of the closing note.
NOTE_TOP = 486.0

# The top of the line saying what this file is.
ITSELF_TOP = 424.0


def weighed(font: hqf_pdf.Font) -> hqf_pdf.Document:
    """The document whose two weights the page reports: pages of text, each under a
    heading of its own."""
    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    handle = document.add_font(font)

    for number in range(1, WEIGHED_PAGES + 1):
        content = hqf_pdf.Content()

        heading = hqf_pdf.TextFlow(handle, 16.0)
        title = f"Chapter {number}"
        heading.draw(content, heading.break_lines(title, ROOM), X, 760.0, ROOM)

        body = hqf_pdf.TextFlow(handle, 11.0, leading=15.0)
        prose = (
            f"This is page {number} of a document written twice over, so that "
            "what packing saves can be weighed rather than claimed."
        )
        body.draw(content, body.break_lines(prose, ROOM), X, 720.0, ROOM)

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


def counted(value: int) -> str:
    """A count of bytes, its thousands held apart by a space."""
    digits = str(value)
    grouped = ""
    for index, digit in enumerate(digits):
        if index > 0 and (len(digits) - index) % 3 == 0:
            grouped += " "
        grouped += digit
    return grouped


def share_saved(flat: int, packed: int) -> int:
    """The share of a document packing saved, in whole per cent.

    Whole numbers throughout: a share written as a fraction would be spelled by
    whatever language drew it, and the two twins must write the same bytes.
    """
    if flat == 0:
        return 0
    return (flat - packed) * 100 // flat


def measured_line() -> str:
    """The line a measuring pass measures: every letter of the Latin alphabets the
    page's face holds, four hundred characters in all."""
    letters = (
        [chr(code) for code in range(ord("A"), ord("Z") + 1)]
        + [chr(code) for code in range(ord("a"), ord("z") + 1)]
        + [chr(code) for code in range(0xC0, 0x100)]
        + [chr(code) for code in range(0x100, 0x180)]
    )
    return "".join(letters[place % len(letters)] for place in range(400))


def measuring(font: hqf_pdf.Font, line: str) -> list[int]:
    """What a document drawing one word weighs once `line` has been measured through
    its font: inside a measuring pass, inside a second one, or outside either."""
    weights = []
    for way in range(3):
        doc = hqf_pdf.Document()
        doc.set_license(_licence.licensed())
        handle = doc.add_font(font)
        if way < 2:
            with doc.measuring():
                handle.glyphs(line)
        else:
            handle.glyphs(line)
        content = hqf_pdf.Content()
        content.draw_text(handle, 12.0, X, 760.0, "Measured")
        page = hqf_pdf.Page.a4()
        page.set_content(content)
        doc.add_page(page)
        weights.append(len(doc.to_bytes()))
    return weights


def unbroken(value: int) -> str:
    """A count of bytes as `counted` writes it, its thousands held apart by a space no
    line is broken at."""
    return counted(value).replace(" ", "\u00a0")


def yes_no(answer: bool, words: Words) -> str:
    """`answer` in `words`."""
    return words.yes_no[0] if answer else words.yes_no[1]


def other_ways(font: hqf_pdf.Font, words: Words) -> list[str]:
    """What the second page says of the document weighed other ways, one line each."""
    off = weighed(font)
    off.set_compression(False)
    weights = [len(off.to_bytes())]
    fastest, default, smallest = (
        hqf_pdf.Compression.fastest(),
        hqf_pdf.Compression.default(),
        hqf_pdf.Compression.smallest(),
    )
    for level in (fastest, default, smallest):
        doc = weighed(font)
        doc.set_compression_level(level)
        weights.append(len(doc.to_bytes()))
    levels = (
        words.levels.replace("{off}", unbroken(weights[0]))
        .replace("{fastest}", unbroken(weights[1]))
        .replace("{default}", unbroken(weights[2]))
        .replace("{smallest}", unbroken(weights[3]))
        .replace("{level_fastest}", str(fastest.level))
        .replace("{level_default}", str(weighed(font).compression_level.level))
        .replace("{level_smallest}", str(smallest.level))
    )

    titled = weighed(font)
    titled.set_metadata(hqf_pdf.Metadata(title=words.title))
    with_dictionary = len(titled.to_bytes())
    titled.set_information_dictionary(False)
    information = (
        words.information.replace("{with}", unbroken(with_dictionary))
        .replace("{without}", unbroken(len(titled.to_bytes())))
        .replace("{written}", yes_no(titled.information_dictionary, words))
    )

    plain = weighed(font)
    run = plain.dry_run()
    dry_run = (
        words.dry_run.replace("{pages}", str(run.pages))
        .replace("{objects}", str(run.objects))
        .replace("{version}", run.version.as_str())
        .replace("{required}", run.required_version.as_str())
        .replace("{warnings}", str(len(run.warnings)))
    )

    data, warnings = plain.to_bytes_reporting()
    streamed = io.BytesIO()
    plain.write_to_reporting(streamed)
    reporting = (
        words.reporting.replace("{bytes}", unbroken(len(data)))
        .replace("{streamed}", unbroken(len(streamed.getvalue())))
        .replace("{warnings}", str(len(warnings)))
    )

    settings = (
        words.settings.replace("{packed}", yes_no(plain.object_streams, words))
        .replace("{linearized}", yes_no(plain.linearized, words))
        .replace("{required}", plain.required_version.as_str())
    )

    covered = weighed(font)
    covered.insert_page(0, hqf_pdf.Page.a4())
    covered.insert_bookmark(0, hqf_pdf.Bookmark(words.cover, 0))
    inserted = words.inserted.replace(
        "{pages}", str(covered.dry_run().pages)
    ).replace("{bookmark}", words.cover)

    inside, held, outside = measuring(font, measured_line())
    measured = (
        words.measured.replace("{inside}", unbroken(inside))
        .replace("{held}", unbroken(held))
        .replace("{outside}", unbroken(outside))
    )

    return [levels, information, dry_run, reporting, settings, inserted, measured]


def second_report(handle, words: Words, lines) -> hqf_pdf.Content:
    """Draw the second page: its heading and `lines`, each a paragraph."""
    content = hqf_pdf.Content()
    title = hqf_pdf.TextFlow(handle, 18.0)
    title.draw(content, title.break_lines(words.other_ways, ROOM), X, TITLE_TOP, ROOM)
    body = hqf_pdf.TextFlow(handle, 10.0, leading=14.0)
    top = WHY_TOP
    for line in lines:
        broken = body.break_lines(line, ROOM)
        body.draw(content, broken, X, top, ROOM)
        top -= body.height(broken) + 10.0
    return content


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    out = _out.output_path(
        Path(_language.file_name("object_streams.pdf", language)).stem
    )

    font = hqf_pdf.Font.from_path(FONT_DIR / "DejaVuSans.ttf")

    spelled_out = weighed(font).to_bytes()
    flat = len(spelled_out)
    packed_document = weighed(font)
    packed_document.set_object_streams(True)
    packed = len(packed_document.to_bytes())

    if len(sys.argv) > 2:
        beside = Path(sys.argv[2])
        beside.parent.mkdir(parents=True, exist_ok=True)
        beside.write_bytes(spelled_out)
        print(f"wrote {beside}: {flat} bytes")

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_object_streams(True)
    handle = document.add_font(font)

    content = hqf_pdf.Content()

    title = hqf_pdf.TextFlow(handle, 18.0)
    title.draw(content, title.break_lines(words.title, ROOM), X, TITLE_TOP, ROOM)

    why = hqf_pdf.TextFlow(handle, 10.0, leading=14.0)
    why.draw(content, why.break_lines(words.why, ROOM), X, WHY_TOP, ROOM)

    subject = hqf_pdf.TextFlow(handle, 10.0, leading=14.0)
    subject.draw(
        content, subject.break_lines(words.subject(), ROOM), X, SUBJECT_TOP, ROOM
    )

    heading = hqf_pdf.TextFlow(handle, 11.0)
    heading.draw(
        content, heading.break_lines(words.weights, ROOM), X, WEIGHTS_TOP, ROOM
    )

    rows = ((words.flat, flat), (words.packed, packed), (words.saved, flat - packed))
    for index, (label, weight) in enumerate(rows):
        top = FIRST_WEIGHT_TOP - WEIGHT_DROP * float(index)
        line = hqf_pdf.TextFlow(handle, 10.0)
        line.draw(content, line.break_lines(label, ROOM), X, top, ROOM)

        stated = f"{counted(weight)} {words.unit}"
        number = hqf_pdf.TextFlow(handle, 10.0)
        number.draw(content, number.break_lines(stated, ROOM), NUMBER_X, top, ROOM)

    note = words.note(share_saved(flat, packed))
    closing = hqf_pdf.TextFlow(handle, 10.0, leading=14.0)
    closing.draw(content, closing.break_lines(note, ROOM), X, NOTE_TOP, ROOM)

    itself = hqf_pdf.TextFlow(handle, 10.0, leading=14.0)
    itself.draw(content, itself.break_lines(words.itself, ROOM), X, ITSELF_TOP, ROOM)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)
    page = hqf_pdf.Page.a4()
    page.set_content(second_report(handle, words, other_ways(font, words)))
    document.add_page(page)

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


if __name__ == "__main__":
    main()
