"""Writes one document twice — the ordinary way, then first page first — and
draws a page stating how much of each a reader must hold before it can show page
one.

The Python twin of the `write_first_page_first` example in Rust. An ordinary PDF
is read from the end: the table saying where every object lives sits after every
object, so a reader has to hold the whole file before it can draw anything at
all. A file written first page first carries the first page, what that page draws
with, and a table stating where every other page begins, all at the head of the
file — so page one appears while the rest is still on its way, and page fifty is
one stretch of bytes to ask for.

The document being measured is built here and written both ways. The page that
reports the two figures is itself written first page first, 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 figures are not language: they are read off the two files.

A second path, if one is given, is where the document that was measured is written
the ordinary way, so that the two spellings of one document can be handed to a
reader side by side.

Usage: python examples/write_first_page_first.py [out.pdf] [ordinary.pdf]
       HQF_PDF_LANG=fr python examples/write_first_page_first.py
"""

from __future__ import annotations

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 measured holds.
#
# The figure a reader waits for is the whole file in the ordinary case, so the longer
# the document, the further apart the two figures are: a document of one page would show
# almost nothing.
MEASURED_PAGES = 200


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

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

    # The line across the top of the page.
    title: str
    # What writing a file first page first does, in two paragraphs.
    why: str
    # The heading over the three figures.
    figures: str
    # What the document being measured is, cut where the page count goes in.
    subject_before: str
    subject_after: str
    # The label on what a reader waits for in the ordinary file.
    ordinary: str
    # The label on what it waits for in the file written first page first.
    reordered: str
    # The label on the difference between the two.
    held_back: str
    # What a figure is counted in.
    unit: str
    # The closing note, cut where the share goes into it.
    note_before: str
    note_after: str
    # The line saying what this very file is.
    itself: str

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

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


# The page in English.
ENGLISH = Words(
    title="What a reader waits for before page one",
    why=(
        "An ordinary PDF is read from the end. The table saying where every "
        "object lives is written after every object, so a reader has to hold "
        "the whole file before it can draw a single page — however few of them "
        "it means to look at.\n"
        "Written first page first, the same document carries page one, what "
        "page one draws with, and a table stating where every other page "
        "begins and ends, all at the head of the file. Page one appears while "
        "the rest is still arriving, and page fifty is one stretch of bytes to "
        "ask for rather than a whole document to fetch."
    ),
    figures="The same document, measured twice",
    subject_before="The document measured here holds ",
    subject_after=(
        " pages, each under a heading of its own, with a list of "
        "those headings a reader can jump from."
    ),
    ordinary="Written the ordinary way",
    reordered="Written first page first",
    held_back="No longer waited for",
    unit="bytes",
    note_before="A reader shown the second file draws page one after ",
    note_after=(
        " per cent of it has arrived. The document is the same one "
        "either way: a reader that knows nothing of any of this opens "
        "the file as it opens every other."
    ),
    itself=(
        "This very file is written first page first, so a reader that "
        "opened it has read one of the two documents being measured."
    ),
)

# The page in French.
FRENCH = Words(
    title="Ce que le lecteur attend avant la page un",
    why=(
        "Un PDF ordinaire se lit par la fin. La table qui dit où vit chaque "
        "objet est écrite après tous les objets : le lecteur doit donc tenir "
        "le fichier entier avant de pouvoir dessiner une seule page — même "
        "s'il n'a l'intention d'en regarder qu'une.\n"
        "Écrit première page en tête, le même document porte la page un, ce "
        "que la page un dessine, et une table qui dit où commence et où finit "
        "chacune des autres pages, le tout au début du fichier. La page un "
        "paraît pendant que le reste arrive, et la page cinquante est une "
        "tranche d'octets à demander plutôt qu'un document entier à "
        "rapatrier."
    ),
    figures="Le même document, mesuré deux fois",
    subject_before="Le document mesuré ici tient en ",
    subject_after=(
        " pages, chacune sous son propre titre, avec la liste de ces "
        "titres d'où le lecteur peut sauter."
    ),
    ordinary="Écrit à l'ordinaire",
    reordered="Écrit première page en tête",
    held_back="Plus attendu",
    unit="octets",
    note_before="Sur le second fichier, le lecteur dessine la page un dès que ",
    note_after=(
        " pour cent est arrivé. Le document est le même des deux côtés : "
        "un lecteur qui ne sait rien de tout cela l'ouvre comme il "
        "ouvre les autres."
    ),
    itself=(
        "Ce fichier-ci est écrit première page en tête : un lecteur qui l'a "
        "ouvert a donc lu l'un des deux documents mesurés."
    ),
)

# 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.
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 writing a file first page first does.
WHY_TOP = 748.0

# The top of the line naming what was measured.
SUBJECT_TOP = 606.0

# The top of the heading over the three figures.
FIGURES_TOP = 560.0

# The top of the first of the three figures.
FIRST_FIGURE_TOP = 534.0

# How far apart two figures sit.
FIGURE_DROP = 20.0

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

# The top of the closing note.
NOTE_TOP = 446.0

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


def measured(font: hqf_pdf.Font) -> hqf_pdf.Document:
    """The document whose two figures the page reports: pages of prose, each under a
    heading of its own, with a list of those headings to jump from."""
    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_metadata(
        hqf_pdf.Metadata(
            title="A document measured from both ends",
            author="HQF Development",
        )
    )
    handle = document.add_font(font)

    for number in range(1, MEASURED_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 a reader waits for can be measured 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)

        document.add_bookmark(hqf_pdf.Bookmark(f"Chapter {number}", number - 1))
    return document


def waited_for(data: bytes) -> int:
    """How many bytes of `data` a reader holds before it can draw page one.

    A file written first page first says so itself: the `/E` entry of its parameter
    dictionary is the offset of the end of the first page, and everything before it
    is what a reader needs. A file written the ordinary way states no such thing, and
    the answer for it is the whole file.
    """
    head = data[: min(1024, len(data))]
    at = head.find(b"/E ")
    if at < 0:
        return len(data)
    at += 3
    while head[at : at + 1] == b" ":
        at += 1
    value = 0
    while head[at : at + 1].isdigit():
        value = value * 10 + int(head[at : at + 1])
        at += 1
    return value


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_waited_for(ordinary: int, reordered: int) -> int:
    """The share of a file a reader holds before page one appears, 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 ordinary == 0:
        return 0
    return reordered * 100 // ordinary


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

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

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

    the_ordinary_way = measured(font).to_bytes()
    reordered_document = measured(font)
    reordered_document.set_linearized(True)
    reordered = reordered_document.to_bytes()

    ordinary = waited_for(the_ordinary_way)
    first_page = waited_for(reordered)

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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_linearized(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.figures, ROOM), X, FIGURES_TOP, ROOM)

    rows = (
        (words.ordinary, ordinary),
        (words.reordered, first_page),
        (words.held_back, ordinary - first_page),
    )
    for index, (label, figure) in enumerate(rows):
        top = FIRST_FIGURE_TOP - FIGURE_DROP * float(index)
        line = hqf_pdf.TextFlow(handle, 10.0)
        line.draw(content, line.break_lines(label, ROOM), X, top, ROOM)

        stated = f"{counted(figure)} {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_waited_for(ordinary, first_page))
    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)

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


if __name__ == "__main__":
    main()
