"""Sets lines of text along paths: round a seal, over an arch, straight across.

The Python twin of the `write_text_path` example in Rust. A path is given as a run of
pieces: the first says where it starts, and every one after it draws. Two numbers are a
point, six are a cubic curve's two control points followed by the point it arrives at.
The path is walked by length, so two letters an inch apart along it are an inch apart on
the page whatever the curve does between them.

The page below draws a seal with a legend curving over its top and another bowed inside
its foot, a title bent over an arch, and three straight paths that show where a line
begins: at the head of the path, halfway along it, or at its far end. The straight paths
are drawn as thin rules, so the line and the path it follows can be read against each
other.

The title, the legends and the captions are held in `Words`, once per language, and
`HQF_PDF_LANG` picks which set is drawn.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The margin the page is laid out inside.
MARGIN = 56.0

# How far the page runs across, between the margins.
WIDTH = 483.0

# Where the seal stands.
SEAL = (297.5, 620.0)

# The outer ring of the seal, in points.
RING = 118.0

# The inner ring, which the legend is written between.
INNER_RING = 98.0

# The circle the legend over the seal is set on.
LEGEND = 101.0

# How far a circle's control points stand from its quarter marks, as a share of the
# radius: the number that turns four cubics into a circle.
KAPPA = 0.5522847498307934

# The four quarter marks of a circle of radius one, anticlockwise from due east.
MARKS = ((1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0))

# Where each of the three straight paths runs.
RULES = (250.0, 200.0, 150.0)

# Where each caption's box starts, in the order `Words` holds them.
CAPTIONS = (480.0, 300.0, 118.0)


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

    # The line at the head of the page.
    title: str
    # The legend curving over the top of the seal.
    seal_over: str
    # The legend bowed inside the foot of the seal.
    seal_under: str
    # The line bent over the arch.
    arch: str
    # What is set along each of the three straight paths.
    starts: tuple[str, str, str]
    # What is written under the seal, the arch and the three rules.
    captions: tuple[str, str, str]


# The page in English.
ENGLISH = Words(
    title="Text set along a path",
    seal_over="HQF DEVELOPMENT",
    seal_under="CERTIFIED COPY",
    arch="A line bent over an arch",
    starts=(
        "At the head of the path",
        "Halfway along it",
        "Stopping where it stops",
    ),
    captions=(
        "The legend follows the ring: over the top it curves with the seal, and "
        "at the foot the path bows the other way, so that the words there stand "
        "upright instead of hanging upside down.",
        "One curve, one line. The path is a single cubic, and the line is set "
        "from its middle, so that what is written stays centred on the arch "
        "however long the words are.",
        "The same words on the same path, begun in three places: at its head, "
        "halfway along it, and stopping where it stops. The rule under each is "
        "the path itself.",
    ),
)

# The page in French.
FRENCH = Words(
    title="Du texte posé le long d’un chemin",
    seal_over="HQF DEVELOPMENT",
    seal_under="COPIE CERTIFIÉE",
    arch="Une ligne courbée sur une arche",
    starts=(
        "Au départ du chemin",
        "À mi-chemin",
        "Jusqu’au bout du chemin",
    ),
    captions=(
        ("La légende suit l’anneau : au-dessus, elle épouse le sceau ; au pied, le "
         "chemin se creuse dans l’autre sens, pour que les mots s’y tiennent droits au"
         " lieu de pendre à l’envers."),
        ("Une courbe, une ligne. Le chemin est une seule cubique, et la ligne est "
         "centrée sur son milieu : le texte reste centré sur l’arche, quelle que soit "
         "la longueur des mots."),
        ("Les mêmes mots sur le même chemin, placés de trois façons : dès son départ, "
         "à mi-chemin, et jusqu’à son bout. Le filet sous chacun est le chemin "
         "lui-même."),
    ),
)

# The page in Dutch.
DUTCH = Words(
    title="Tekst gezet langs een pad",
    seal_over="HQF DEVELOPMENT",
    seal_under="GEWAARMERKTE KOPIE",
    arch="Een regel gebogen over een boog",
    starts=(
        "Aan het begin van het pad",
        "Halverwege",
        "Stoppend waar het stopt",
    ),
    captions=(
        "Het onderschrift volgt de ring: bovenaan buigt het met het zegel mee, en "
        "onderaan buigt het pad de andere kant op, zodat de woorden daar rechtop "
        "staan in plaats van ondersteboven te hangen.",
        "Eén curve, één regel. Het pad is één kubische curve, en de regel wordt "
        "vanuit het midden gezet, zodat wat er staat gecentreerd blijft op de boog, "
        "hoe lang de woorden ook zijn.",
        "Dezelfde woorden op hetzelfde pad, op drie plekken begonnen: aan het begin, "
        "halverwege, en stoppend waar het stopt. De lijn onder elk is het pad zelf.",
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Texto composto ao longo de um traçado",
    seal_over="HQF DEVELOPMENT",
    seal_under="CÓPIA CERTIFICADA",
    arch="Uma linha dobrada sobre um arco",
    starts=(
        "No início do traçado",
        "A meio caminho",
        "A parar onde ele para",
    ),
    captions=(
        "A legenda segue o anel: por cima curva com o selo, e no pé o traçado "
        "dobra-se ao contrário, para que as palavras aí fiquem direitas em vez de "
        "penderem de pernas para o ar.",
        "Uma curva, uma linha. O traçado é uma única cúbica, e a linha é composta a "
        "partir do seu meio, para que o que está escrito fique centrado no arco seja "
        "qual for o comprimento das palavras.",
        "As mesmas palavras no mesmo traçado, começadas em três sítios: no início, a "
        "meio caminho, e a parar onde ele para. O filete sob cada uma é o próprio "
        "traçado.",
    ),
)

# The page in Italian.
ITALIAN = Words(
    title="Testo composto lungo un tracciato",
    seal_over="HQF DEVELOPMENT",
    seal_under="COPIA CONFORME",
    arch="Una riga curvata su un arco",
    starts=(
        "All’inizio del tracciato",
        "A metà strada",
        "Fermandosi dove si ferma",
    ),
    captions=(
        "La legenda segue l’anello: sopra si curva con il sigillo, e al piede il "
        "tracciato si piega al contrario, così le parole lì stanno dritte invece di "
        "pendere capovolte.",
        "Una curva, una riga. Il tracciato è una sola cubica, e la riga è composta "
        "dal suo centro, così ciò che è scritto resta centrato sull’arco per quanto "
        "lunghe siano le parole.",
        "Le stesse parole sullo stesso tracciato, iniziate in tre punti: all’inizio, "
        "a metà strada, e fermandosi dove si ferma. Il filetto sotto ciascuna è il "
        "tracciato stesso.",
    ),
)

# The page in Spanish.
SPANISH = Words(
    title="Texto compuesto a lo largo de un trazado",
    seal_over="HQF DEVELOPMENT",
    seal_under="COPIA CERTIFICADA",
    arch="Una línea curvada sobre un arco",
    starts=(
        "Al principio del trazado",
        "A mitad de camino",
        "Acabando donde acaba",
    ),
    captions=(
        "La leyenda sigue el anillo: por arriba se curva con el sello, y en el pie el "
        "trazado se arquea al revés, para que las palabras de ahí queden derechas en "
        "vez de colgar cabeza abajo.",
        "Una curva, una línea. El trazado es una sola cúbica, y la línea se compone "
        "desde su centro, para que lo escrito quede centrado en el arco sea cual sea "
        "la longitud de las palabras.",
        "Las mismas palabras en el mismo trazado, empezadas en tres sitios: al "
        "principio, a mitad de camino, y acabando donde acaba el trazado. La raya "
        "bajo cada una es el propio trazado.",
    ),
)

# The page in German.
GERMAN = Words(
    title="Text entlang eines Pfads gesetzt",
    seal_over="HQF DEVELOPMENT",
    seal_under="BEGLAUBIGTE KOPIE",
    arch="Eine Zeile, über einen Bogen gelegt",
    starts=(
        "Am Anfang des Pfads",
        "Auf halber Strecke",
        "Endet, wo er endet",
    ),
    captions=(
        "Die Umschrift folgt dem Ring: Oben krümmt sie sich mit dem Siegel, und am "
        "Fuß biegt sich der Pfad andersherum, sodass die Wörter dort aufrecht stehen, "
        "statt kopfüber zu hängen.",
        "Eine Kurve, eine Zeile. Der Pfad ist eine einzige kubische Kurve, und die "
        "Zeile wird von ihrer Mitte aus gesetzt, sodass das Geschriebene auf dem "
        "Bogen zentriert bleibt, wie lang die Wörter auch sind.",
        "Dieselben Wörter auf demselben Pfad, an drei Stellen begonnen: an seinem "
        "Anfang, auf halber Strecke und so, dass sie enden, wo er endet. Die Linie "
        "unter jedem ist der Pfad selbst.",
    ),
)


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


def beginnings() -> tuple[hqf_pdf.PathStart, hqf_pdf.PathStart, hqf_pdf.PathStart]:
    """The three places along a path a line can begin, in the order the rules are
    drawn."""
    return (
        hqf_pdf.PathStart.Beginning,
        hqf_pdf.PathStart.Middle,
        hqf_pdf.PathStart.End,
    )


def arc(
    radius: float, mark: tuple[float, float], nxt: tuple[float, float]
) -> tuple[float, float, float, float, float, float]:
    """A quarter of a circle of radius `radius` about the seal, running from the quarter
    mark `mark` to the quarter mark `nxt`.

    The two marks are a quarter turn apart, in either order, so the same arithmetic
    draws the circle anticlockwise and the legend clockwise over the top of it.
    """
    pull = KAPPA * radius
    return (
        nxt[0] * pull + (SEAL[0] + mark[0] * radius),
        nxt[1] * pull + (SEAL[1] + mark[1] * radius),
        mark[0] * pull + (SEAL[0] + nxt[0] * radius),
        mark[1] * pull + (SEAL[1] + nxt[1] * radius),
        SEAL[0] + nxt[0] * radius,
        SEAL[1] + nxt[1] * radius,
    )


def over_the_seal() -> list[tuple[float, ...]]:
    """The path the legend over the seal follows: the left of the ring, over the top, to
    the right of it."""
    return [
        (SEAL[0] - LEGEND, SEAL[1]),
        arc(LEGEND, MARKS[2], MARKS[1]),
        arc(LEGEND, MARKS[1], MARKS[0]),
    ]


def under_the_seal() -> list[tuple[float, ...]]:
    """The path the legend at the foot of the seal follows: one curve bowing downward,
    so that the words along it stand upright."""
    return [
        (SEAL[0] - 80.0, SEAL[1] - 36.0),
        (
            SEAL[0] - 34.0,
            SEAL[1] - 96.0,
            SEAL[0] + 34.0,
            SEAL[1] - 96.0,
            SEAL[0] + 80.0,
            SEAL[1] - 36.0,
        ),
    ]


def the_arch() -> list[tuple[float, ...]]:
    """The arch the title is bent over."""
    return [
        (MARGIN, 330.0),
        (
            MARGIN + 145.0,
            420.0,
            MARGIN + WIDTH - 145.0,
            420.0,
            MARGIN + WIDTH,
            330.0,
        ),
    ]


def straight(y: float) -> list[tuple[float, ...]]:
    """A path running straight across the page at `y`."""
    return [(MARGIN, y), (MARGIN + WIDTH, y)]


def ring(content: hqf_pdf.Content, radius: float) -> None:
    """Draws a ring of the seal."""
    content.move_to(SEAL[0] + radius, SEAL[1])
    for turn in range(len(MARKS)):
        content.curve_to(*arc(radius, MARKS[turn], MARKS[(turn + 1) % len(MARKS)]))
    content.close_path()
    content.stroke()


def rule(content: hqf_pdf.Content, y: float) -> None:
    """Draws a rule where a straight path runs."""
    content.move_to(MARGIN, y)
    content.line_to(MARGIN + WIDTH, y)
    content.stroke()


def caption(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, top: float, color: hqf_pdf.Rgb, text: str
) -> None:
    """Writes a caption in a column the width of the page."""
    flow = hqf_pdf.TextFlow(font, 8.5, leading=12.0, color=color)
    lines = flow.break_lines(text, WIDTH)
    flow.draw(content, lines, MARGIN, top, WIDTH)


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 = _out.output_path(Path(_language.file_name("text_path.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.DEFAULT_FONT))

    content = hqf_pdf.Content()
    content.draw_text(font, 14.0, MARGIN, 800.0, words.title)

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb(0.25, 0.35, 0.7))
    content.set_line_width(1.5)
    ring(content, RING)
    ring(content, INNER_RING)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.25, 0.35, 0.7))
    hqf_pdf.TextPath(
        font,
        words.seal_over,
        14.0,
        over_the_seal(),
        start=hqf_pdf.PathStart.Middle,
    ).draw(content)
    hqf_pdf.TextPath(
        font,
        words.seal_under,
        12.0,
        under_the_seal(),
        start=hqf_pdf.PathStart.Middle,
    ).draw(content)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.1, 0.45, 0.25))
    hqf_pdf.TextPath(
        font, words.arch, 20.0, the_arch(), start=hqf_pdf.PathStart.Middle
    ).draw(content)
    content.restore_state()

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.8))
    content.set_line_width(0.5)
    for y in RULES:
        rule(content, y)
    content.restore_state()

    for y, start, text in zip(RULES, beginnings(), words.starts):
        hqf_pdf.TextPath(font, text, 12.0, straight(y), start=start).draw(content)

    for top, text in zip(CAPTIONS, words.captions):
        caption(content, font, top, hqf_pdf.Rgb.gray(0.35), text)

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

    written = document.write(out)
    print(f"wrote {out}: {written} bytes, {3 + len(RULES)} lines along a path")


if __name__ == "__main__":
    main()
