"""Sets a page in a font read from a Type 1 program, and states what it says of itself.

The Python twin of the `write_type_one_font` example in Rust. Adobe's first font format
is not a table anybody can look a glyph up in: it is a PostScript program whose glyphs
are ciphered, and every measurement below is read out of it rather than written in by
hand. The program itself is carried into the file whole.

The face is `HqfStroke`, HQF Development's own: a stroke face built by
`scripts/build_type1_sample.py`, committed beside the fonts the tests run against.

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

Usage: python examples/write_type_one_font.py [out.pdf] [face.pfb]
       HQF_PDF_LANG=fr python examples/write_type_one_font.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 three lines set in the face itself.
    shown: str
    # The three lines, in the capitals the face draws.
    samples: tuple[str, str, str]
    # The label over what the program states about itself.
    stated: str
    # The sentence those figures are put into.
    facts: str
    # The label over the weight.
    weight: str
    # The sentence the two weights are put into.
    weighed: str
    # The label over what is left for a later version.
    later: str
    # Why the whole program travels, and what it would take not to.
    postponed: str
    # What such a font cannot do.
    caveat: str


# The page in English.
ENGLISH = Words(
    title="A page set in a Type 1 font",
    lead=(
        "The three lines below are drawn from a font program in Adobe's first format. "
        "It is not a font file with tables to look a glyph up in: it is a PostScript "
        "program, its glyphs ciphered one by one, and the library reads it to find out "
        "how wide each of them is and which code reaches it. The program is then "
        "carried into this file whole, and the reader draws from those very bytes."
    ),
    shown="Drawn from the program",
    samples=(
        "HQF DEVELOPMENT",
        "ABCDEFGHIJKLM NOPQRSTUVWXYZ 0123456789",
        "A STROKE FACE, READ AND CARRIED WHOLE.",
    ),
    stated="What the program states about itself",
    facts=(
        "It calls itself %name% and holds %glyphs% glyphs, of which %reached% are "
        "reached by a code. Every glyph stands in one box, whose corners are %low% and "
        "%high%; a vertical stem is %stem% thousandths of an em thick, and an underline "
        "sits %underline% below the line. Not one of those figures is written into this "
        "page: each is read out of the program."
    ),
    weight="What it weighs",
    weighed=(
        "The program itself is %program% bytes on disk, and a page carrying it weighs "
        "%document% bytes. Both figures are measured by the program that drew this "
        "page, not written in by hand."
    ),
    later="What travels with it, and why",
    postponed=(
        "Every other kind of font this library carries travels light: only the letters "
        "a page actually draws go into the file, so a page that says one word carries "
        "the letters of that word and not a whole alphabet. A Type 1 program does not. "
        "It travels whole, and the reason is in the format itself: each glyph is "
        "ciphered on its own inside the program, so keeping some and dropping the rest "
        "means deciphering the program, rewriting its list of glyphs, and ciphering it "
        "again — while holding on to the pieces of outline that several glyphs share, "
        "and to the glyphs that are built out of two others. That is a piece of work of "
        "its own, and it is deliberately left to a later version of this library. It "
        "costs nothing on a face of a few dozen glyphs. It costs real bytes on a large "
        "one: a face of sixty thousand bytes travels sixty thousand bytes even where "
        "the page shows three words."
    ),
    caveat=(
        "A Type 1 font is a simple font: its codes are one byte, so at most 256 of its "
        "glyphs are reachable at a time and it never sets text down the page. Which "
        "code reaches which glyph is the program's own business — this file repeats the "
        "program's own names for them."
    ),
)

# The page in French.
FRENCH = Words(
    title="Une page composée dans une police de type 1",
    lead=(
        "Les trois lignes ci-dessous sont dessinées par un programme de police écrit "
        "dans le premier format d'Adobe. Ce n'est pas un fichier de police avec des "
        "tables où chercher un dessin : c'est un programme PostScript, dont chaque "
        "dessin est chiffré à part, et la bibliothèque le lit pour savoir la largeur de "
        "chacun et le code qui l'atteint. Le programme est ensuite transporté entier "
        "dans ce fichier, et le lecteur dessine à partir de ces octets-là."
    ),
    shown="Dessiné par le programme",
    samples=(
        "HQF DEVELOPMENT",
        "ABCDEFGHIJKLM NOPQRSTUVWXYZ 0123456789",
        "UNE POLICE DE TRAITS, LUE ET PORTÉE ENTIÈRE.",
    ),
    stated="Ce que le programme dit de lui-même",
    facts=(
        "Il s'appelle %name% et porte %glyphs% dessins, dont %reached% sont atteints "
        "par un code. Chaque dessin tient dans une seule boîte, dont les coins sont "
        "%low% et %high% ; un fût vertical fait %stem% millièmes de cadratin "
        "d'épaisseur, et un soulignement se pose %underline% sous la ligne. Aucun de "
        "ces chiffres n'est écrit dans cette page : chacun est lu dans le programme."
    ),
    weight="Ce que cela pèse",
    weighed=(
        "Le programme lui-même pèse %program% octets sur le disque, et une page qui le "
        "transporte pèse %document% octets. Les deux chiffres sont mesurés par le "
        "programme qui a dessiné cette page, pas écrits à la main."
    ),
    later="Ce qui voyage avec, et pourquoi",
    postponed=(
        "Toutes les autres sortes de polices que cette bibliothèque transporte voyagent "
        "légères : seules les lettres réellement dessinées entrent dans le fichier, si "
        "bien qu'une page qui écrit un mot transporte les lettres de ce mot et pas un "
        "alphabet entier. Un programme de type 1, lui, voyage entier, et la raison "
        "tient au format lui-même : chaque dessin y est chiffré à part, donc n'en "
        "garder qu'une partie veut dire déchiffrer le programme, réécrire sa liste de "
        "dessins, puis tout rechiffrer — en gardant les morceaux de tracé que plusieurs "
        "lettres se partagent, et les lettres fabriquées à partir de deux autres. C'est "
        "un chantier à lui tout seul, et il est volontairement laissé à une version "
        "suivante de cette bibliothèque. Cela ne coûte rien sur une police de quelques "
        "dizaines de dessins. Cela coûte de vrais octets sur une grande : une police de "
        "soixante mille octets voyage soixante mille octets, même là où la page ne "
        "montre que trois mots."
    ),
    caveat=(
        "Une police de type 1 est une police simple : ses codes tiennent sur un octet, "
        "donc 256 de ses dessins au plus sont atteignables à la fois, et elle ne "
        "compose jamais de haut en bas. Quel code atteint quel dessin ne regarde que le "
        "programme — ce fichier reprend les noms que le programme leur donne."
    ),
)

# 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 Type 1 program the page is set in when the caller names none.
DEFAULT_FACE = _out.ROOT / "crates" / "hqf-pdf" / "tests" / "fonts" / "HqfStroke.pfb"


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("\u00a0")
        out.append(digit)
    return "".join(out)


def reached(face: hqf_pdf.Type1Font) -> int:
    """How many of the program's glyphs a code reaches."""
    return sum(1 for code in range(256) if face.character_at(code) is not None)


def corners(face: hqf_pdf.Type1Font) -> tuple[str, str]:
    """The two corners of the box a face states, as the page writes them."""
    llx, lly, urx, ury = face.bbox
    return f"{llx:g} · {lly:g}", f"{urx:g} · {ury:g}"


def weighed(words: Words, face: hqf_pdf.Type1Font) -> int:
    """What a page holding nothing but the three samples weighs.

    It is measured on a page of its own: a page that states its own weight never
    settles, because writing the figure changes the figure.
    """
    doc = hqf_pdf.Document()
    doc.set_license(_licence.licensed())
    handle = doc.add_type1_font(face)

    content = hqf_pdf.Content()
    top = 760.0
    for sample in words.samples:
        top = block(content, handle, 15.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, face: hqf_pdf.Type1Font, prose: Path, program: int, document: int
) -> bytes:
    """Draws the whole page."""
    doc = hqf_pdf.Document()
    doc.set_license(_licence.licensed())
    text = doc.add_font(hqf_pdf.Font.from_path(prose))
    drawn = doc.add_type1_font(face)

    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.shown) - 14.0
    for sample in words.samples:
        top = block(content, drawn, 15.0, top, sample) - 10.0

    top -= 14.0
    top = block(content, text, 12.0, top, words.stated) - 10.0
    low, high = corners(face)
    stem = "—" if face.stem_v is None else f"{face.stem_v:g}"
    underline = "—" if face.underline is None else f"{-face.underline[0]:g}"
    stated = (
        words.facts.replace("%name%", face.name)
        .replace("%glyphs%", str(len(face.glyph_names)))
        .replace("%reached%", str(reached(face)))
        .replace("%low%", low)
        .replace("%high%", high)
        .replace("%stem%", stem)
        .replace("%underline%", underline)
    )
    top = block(content, text, 10.0, top, stated) - 20.0

    top = block(content, text, 12.0, top, words.weight) - 10.0
    said = words.weighed.replace("%program%", spaced(program)).replace(
        "%document%", spaced(document)
    )
    top = block(content, text, 10.0, top, said) - 20.0

    top = block(content, text, 12.0, top, words.later) - 10.0
    top = block(content, text, 10.0, top, words.postponed) - 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("type_one_font.pdf", language)).stem
    )
    face_path = _out.font_path() if len(__import__("sys").argv) > 2 else DEFAULT_FACE

    data = Path(face_path).read_bytes()
    face = hqf_pdf.Type1Font.from_bytes(data)

    document = weighed(words, face)
    drawn = build(words, face, _out.DEFAULT_FONT, len(data), document)

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


if __name__ == "__main__":
    main()
