"""Sets a whole page in fonts the file does not carry, and weighs what that saves.

The Python twin of the `write_no_font_at_all` example in Rust. A reader is required to
draw fourteen fonts whether the file carries them or not, so a document that names one
of them writes no font program: a few hundred bytes of dictionary instead of the tens of
kilobytes a subset costs. The page is set in four of them, and the figures it states are
measured by the program, not written in by hand.

Both sets of words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf


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

    # The page's title.
    title: str
    # What the page is about.
    lead: str
    # The label over the four samples.
    faces: str
    # What each of the four samples says.
    samples: tuple[str, str, str, str]
    # The heading over the weight.
    weight: str
    # The sentence the two measured weights are put into.
    saved: str
    # What such a font cannot do.
    caveat: str


# The page in English.
ENGLISH = Words(
    title="A page that carries no font",
    lead=(
        "Every one of the lines below is set in a font this file does not hold. A "
        "reader draws them from its own store, which is what the standard asks of it, "
        "so nothing of the typefaces travels with the document."
    ),
    faces="Four of the fourteen",
    samples=(
        "Helvetica, the one without serifs.",
        "Times Bold Italic, and it is already accented: déjà, ç, ù, ô, ï.",
        "Courier, where every letter is the same width.",
        "Σ √ ∫ αβγ ≥ ∞",
    ),
    weight="What it saves",
    saved=(
        "Those four lines, on a page of their own, weigh %light% bytes. The same four "
        "lines, with one font carried inside the file, weigh %heavy%. Both figures are "
        "measured by the program that drew this page, not written in by hand."
    ),
    caveat=(
        "It is not free. A file claiming an archival or accessibility standard may not "
        "do this — those standards want every font carried — and these faces draw only "
        "the letters their own encoding reaches, so a writing system outside it needs "
        "a font the file does carry."
    ),
)

# The page in French.
FRENCH = Words(
    title="Une page qui ne transporte aucune police",
    lead=(
        "Chacune des lignes ci-dessous est composée dans une police que ce fichier ne "
        "contient pas. Le lecteur les prend dans sa propre réserve, ce que la norme "
        "lui impose, et rien des caractères ne voyage avec le document."
    ),
    faces="Quatre des quatorze",
    samples=(
        "Helvetica, celle qui n'a pas d'empattements.",
        "Times gras italique, et déjà accentuée : ç, ù, ô, ï, œ.",
        "Courier, où chaque lettre occupe la même largeur.",
        "Σ √ ∫ αβγ ≥ ∞",
    ),
    weight="Ce que cela économise",
    saved=(
        "Ces quatre lignes, sur une page à elles seules, pèsent %light% octets. Les "
        "mêmes quatre lignes, avec une police transportée dans le fichier, en pèsent "
        "%heavy%. Les deux chiffres sont mesurés par le programme qui a dessiné cette "
        "page, pas écrits à la main."
    ),
    caveat=(
        "Ce n'est pas gratuit. Un fichier qui réclame une norme d'archivage ou "
        "d'accessibilité n'a pas le droit de faire cela — ces normes veulent toute "
        "police transportée — et ces caractères ne dessinent que les lettres que leur "
        "propre encodage atteint : une écriture en dehors exige une police que le "
        "fichier porte vraiment."
    ),
)


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

# The left edge of everything on the page.
LEFT = 72.0

# How wide a block of text is.
WIDTH = 450.0

# The four the page is set in, in the order it sets them.
FACES = (
    hqf_pdf.StandardFont.helvetica,
    hqf_pdf.StandardFont.times_bold_italic,
    hqf_pdf.StandardFont.courier,
    hqf_pdf.StandardFont.symbol,
)


def block(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    size: float,
    top: float,
    text: str,
) -> float:
    """Sets a block of words at `top`, and hands back the ordinate it ends at."""
    flow = hqf_pdf.TextFlow(handle, size)
    lines = flow.break_lines(text, WIDTH)
    # The binding opens the text object itself, so opening another here would write a
    # pair of operators its twin in Rust does not.
    flow.draw(content, lines, LEFT, top, WIDTH)
    return top - flow.height(lines)


def spaced(count: int) -> str:
    """A count with a no-break space between its thousands."""
    digits = str(count)
    out = []
    for index, digit in enumerate(digits):
        if index > 0 and (len(digits) - index) % 3 == 0:
            out.append(" ")
        out.append(digit)
    return "".join(out)


def weighed(words: Words, carried: Path | None) -> int:
    """What a page holding nothing but the four samples weighs.

    This is the measurement the page reports. It is made on a page of its own so that
    the prose around it — and the figures themselves — weigh nothing in it.
    """
    doc = hqf_pdf.Document()
    doc.set_license(_licence.licensed())
    if carried is None:
        handles = [doc.add_standard_font(face()) for face in FACES]
    else:
        one = doc.add_font(hqf_pdf.Font.from_path(carried))
        handles = [one] * len(words.samples)

    content = hqf_pdf.Content()
    top = 760.0
    for handle, sample in zip(handles, words.samples):
        top = block(content, handle, 13.0, top, sample) - 10.0

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    doc.add_page(page)
    return len(doc.to_bytes())


def build(words: Words, light: int, heavy: int) -> bytes:
    """Draws the whole page, stating the two weights it measured."""
    doc = hqf_pdf.Document()
    doc.set_license(_licence.licensed())
    handles = [doc.add_standard_font(face()) for face in FACES]
    text = handles[0]

    content = hqf_pdf.Content()
    top = 760.0
    top = block(content, text, 18.0, top, words.title) - 14.0
    top = block(content, text, 10.0, top, words.lead) - 24.0

    top = block(content, text, 12.0, top, words.faces) - 12.0
    for handle, sample in zip(handles, words.samples):
        top = block(content, handle, 13.0, top, sample) - 10.0

    top -= 14.0
    top = block(content, text, 12.0, top, words.weight) - 10.0
    said = words.saved.replace("%light%", spaced(light)).replace(
        "%heavy%", spaced(heavy)
    )
    top = block(content, text, 10.0, top, said) - 20.0

    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    block(content, text, 9.0, top, words.caveat)

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


def main() -> None:
    """Writes the page."""
    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("no_font_at_all.pdf", language)).stem
    )

    light = weighed(words, None)
    heavy = weighed(words, _out.font_path())
    data = build(words, light, heavy)

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


if __name__ == "__main__":
    main()
