"""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",
        "S'arrêtant où il s'arrête",
    ),
    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 "
        "part de son milieu : ce qui est écrit reste centré sur l'arche quelle "
        "que soit la longueur des mots.",
        "Les mêmes mots sur le même chemin, commencés à trois endroits : à son "
        "départ, à mi-chemin, et s'arrêtant où il s'arrête. Le filet sous "
        "chacun est le chemin lui-même.",
    ),
)


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


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()
