"""Inks the press carries on plates of their own, at every tint.

The Python twin of the `write_spot_color` example in Rust. A spot colour is not
mixed out of the process inks: it is an ink of its own, and a colour in its space
is one number — how much of it goes down. What that number looks like where the
ink is not to hand, on a screen or on a press that does not carry it, is what the
tint transform says.

The second page sets a run list in those same two inks and in nothing else: the
heading on a full-strength plate, every other line on a tint of it, the total on
the second ink, the rules in both, and a closing paragraph whose runs each name
an ink. Everything that paints takes a colour the document carries exactly where
it takes a device one — a cell's background, a cell's text, a row, a table's
rules, a run of styled text, a stamp.

What the two sheets say is written in the language `HQF_PDF_LANG` names. The names
of the inks are not: a colorant is what the plate answers to, the file writes it,
and a page that renamed it would name a plate the press has not got. Neither are
the sheet counts, the prices or the tints.

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

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The left edge of everything, and the width of the sheet the page shows.
LEFT = 70.0
WIDTH = 445.0

# The left edge of each tint swatch, and the size of one.
TINT_X = (70.0, 115.0, 160.0, 205.0, 250.0, 295.0, 340.0, 385.0, 430.0, 475.0)
TINT_SIZE = (40.0, 56.0)

# The top of the run list on the second page.
LIST_TOP = 700.0

# Where the head of a sheet sits, and where the two lines under it do.
HEAD_BASELINE = 780.0
LEAD_BASELINES = (762.0, 748.0)

# Where the rule at the foot of the second sheet is drawn.
CLOSING_RULE = 92.0

# The size the closing paragraph is set at, and how far apart its lines sit.
PROSE_SIZE = 10.5
PROSE_LEADING = 15.0

# The two inks the work is set in, and the colorant every plate answers to. A colorant
# is what the plate is called on the press: the file writes it, and no language renames
# it.
BLUE = "Corporate Blue"
GOLD = "Corporate Gold"
ALL_PLATES = "All"

# The tint the panel behind the heading is laid at, which the caption under it spells
# out in words.
PANEL_TINT = 0.15

# The tint the shaded lines of the run list are laid at, which the note under it spells
# out in words.
SHADED_TINT = 0.08

# The strength the closing paragraph is drawn at, which it says of itself.
PROSE_TINT = 0.9

# The sizes the two sheets are set in, in points.
HEAD_SIZE = 15.0
LEAD_SIZE = 10.0
SWATCH_SIZE = 7.0
CAPTION_SIZE = 10.0
SHEET_TITLE_SIZE = 26.0
SHEET_LINE_SIZE = 11.0
MARK_SIZE = 9.0
CELL_SIZE = 9.0
TOTAL_SIZE = 9.5
CLOSING_SIZE = 8.5

# The ten tints each ink is shown at. What each is called is read off the tint itself,
# so no language can label a swatch with a strength it is not laid at.
TINTS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)

# What the nine lines come to.
TOTAL = "3 061.00"


def crosshairs(bottom: float, height: float) -> tuple[tuple[float, float], ...]:
    """Where the crosshairs stand around a sheet whose foot is at `bottom` and which is
    `height` tall.

    A page says how many there are, so the count and the word have to agree.
    """
    return (
        (LEFT - 16.0, bottom - 16.0),
        (LEFT + WIDTH + 16.0, bottom - 16.0),
        (LEFT - 16.0, bottom + height + 16.0),
        (LEFT + WIDTH + 16.0, bottom + height + 16.0),
    )


def tint_name(tint: float) -> str:
    """What one tint is called under its swatch."""
    return f"{tint * 100.0:.0f}%"


class Plates(Enum):
    """Which plates a line of the run list takes."""

    FIRST = 0
    SECOND = 1
    BOTH = 2

    def named(self, words: Words) -> str:
        """What this run of plates is called, in the words of a language."""
        return words.plates[self.value]


# One line of the run list: how many sheets it runs to, which plates it takes and what
# it comes to. What is being printed is a word, and it lives with the other words of its
# language.
ITEMS = (
    ("5 000", Plates.FIRST, "412.00"),
    ("2 000", Plates.FIRST, "196.00"),
    ("2 000", Plates.BOTH, "268.00"),
    ("3 000", Plates.SECOND, "184.00"),
    ("1 000", Plates.BOTH, "590.00"),
    ("750", Plates.BOTH, "445.00"),
    ("5 000", Plates.FIRST, "388.00"),
    ("1 500", Plates.FIRST, "242.00"),
    ("12", Plates.BOTH, "336.00"),
)


@dataclass(frozen=True)
class Words:
    """The words the two sheets are written in, one set per language.

    The names of the inks are not among them, nor the sheet counts, the prices or the
    tints.
    """

    # What the first sheet is called.
    title: str
    # The two lines under it, which say what a spot colour is.
    lead: tuple[str, ...]
    # What stands after the name of the first ink over its ramp of tints.
    first_ramp: str
    # What stands after the name of the second over its own.
    second_ramp: str
    # What the piece of work set in the two inks is called.
    sheet_title: str
    # The line inside it, which says what is laid over what.
    sheet_line: str
    # The line under it, which says what the crosshairs are for.
    marks: str
    # What the second sheet is called.
    list_title: str
    # The two lines under it, which say how far a carried colour reaches.
    list_lead: tuple[str, ...]
    # What heads each column of the run list, left to right.
    headings: tuple[str, ...]
    # What each line of the run list is printing, in the order `ITEMS` runs them.
    items: tuple[str, ...]
    # What each run of plates is called: the first alone, the second alone, then both.
    plates: tuple[str, ...]
    # What the last row of the run list is called.
    total: str
    # The three runs of the note under the list, the middle one of which is set in the
    # second ink.
    note: tuple[str, ...]
    # The paragraph under it, drawn in one flow.
    prose: str
    # The mark laid across the whole of the run list.
    stamp: str
    # What stands before the name of the first ink in the closing line.
    quoted_before: str
    # What stands between the two names.
    quoted_between: str
    # What stands after the second.
    quoted_after: str


# The two sheets in English.
ENGLISH = Words(
    title="Inks the press carries, on plates of their own",
    lead=(
        "A spot colour is one number, not four: how much of that ink goes down. "
        "Where the ink is not",
        "to hand, the tint transform the file carries shows it — which is what "
        "these swatches are.",
    ),
    first_ramp=", one plate, ten tints",
    second_ramp=", a second plate",
    sheet_title="Two inks, one sheet",
    sheet_line="Set in the second ink, over a fifteen percent tint of the first.",
    marks="The four crosshairs are set in the colorant every plate answers to, "
    "which is what lines them up.",
    list_title="The same two inks, through the layout",
    list_lead=(
        "A colour the document carries reaches a cell, a row, a rule and a run "
        "of styled text the",
        "way a colour the device answers for does. Not a drop of process ink "
        "goes down below.",
    ),
    headings=("Item", "Sheets", "Plates", "Price"),
    items=(
        "Letterhead, A4",
        "Letterhead, A5",
        "Business cards, both sides",
        "Compliments slip",
        "Presentation folder",
        "Report cover, laminated",
        "Window envelope, DL",
        "Wallet envelope, C4",
        "Exhibition panel",
    ),
    plates=("First", "Second", "Both"),
    total="Total, nine items, two plates",
    note=(
        "The heading stands on a full plate of the first ink, ",
        "the total on the second",
        ", and the shaded lines on an eight percent tint of the first. One run "
        "of this sentence is set in each of the two.",
    ),
    prose="An ink of its own is what a house colour is bought as: the press "
    "carries it on a plate of its own, so it goes down at the same strength on "
    "every sheet of every run, which four process inks laid over each other "
    "cannot promise. It costs a plate, so it is spent on the marks a reader "
    "recognises the house by — the name, the rule under it, the panel behind a "
    "heading — and the rest of the work is left to the process inks. This "
    "paragraph is one flow of text, drawn in the first ink at ninety percent, "
    "and the words of it were measured and broken to the width of the list "
    "above.",
    stamp="SPECIMEN",
    quoted_before="Quoted in two inks: ",
    quoted_between=" and ",
    quoted_after=", each on a plate of its own.",
)

# The two sheets in French.
FRENCH = Words(
    title="Des encres que la presse porte, chacune sur sa plaque",
    lead=(
        "Un ton direct est un seul nombre, pas quatre : la quantité d'encre qui "
        "descend. Là où l'encre",
        "manque, la transformation de teinte du fichier la montre — c'est ce que "
        "sont ces pastilles.",
    ),
    first_ramp=", une plaque, dix teintes",
    second_ramp=", une seconde plaque",
    sheet_title="Deux encres, une feuille",
    sheet_line="Seconde encre, sur une teinte à quinze pour cent de la première.",
    marks="Les quatre croix sont tracées dans le colorant auquel chaque plaque "
    "répond : c'est ce qui les cale.",
    list_title="Les deux mêmes encres, à travers la mise en page",
    list_lead=(
        "Une couleur que le document porte atteint une cellule, une rangée, un "
        "filet et un passage",
        "stylé comme le fait une couleur d'appareil. Pas une goutte d'encre de "
        "quadrichromie dessous.",
    ),
    headings=("Article", "Feuilles", "Plaques", "Prix"),
    items=(
        "Papier à en-tête, A4",
        "Papier à en-tête, A5",
        "Cartes de visite, recto verso",
        "Carte de compliments",
        "Chemise de présentation",
        "Couverture de rapport, pelliculée",
        "Enveloppe à fenêtre, DL",
        "Enveloppe à poche, C4",
        "Panneau d'exposition",
    ),
    plates=("Première", "Seconde", "Les deux"),
    total="Total, neuf articles, deux plaques",
    note=(
        "Le titre tient sur une plaque pleine de la première encre, ",
        "le total sur la seconde",
        ", et les lignes teintées sur une teinte à huit pour cent de la "
        "première. Un passage de cette phrase est composé dans chacune des deux.",
    ),
    prose="Une encre à soi, voilà ce qu'on achète avec une couleur de maison : "
    "la presse la porte sur une plaque à elle, donc elle descend à la même force "
    "sur chaque feuille de chaque tirage, ce que quatre encres de quadrichromie "
    "posées l'une sur l'autre ne peuvent pas promettre. Elle coûte une plaque, "
    "donc on la dépense sur les marques auxquelles un lecteur reconnaît la "
    "maison — le nom, le filet dessous, le panneau derrière un titre — et le "
    "reste du travail est laissé aux encres de quadrichromie. Ce paragraphe est "
    "une seule coulée de texte, tirée dans la première encre à quatre-vingt-dix "
    "pour cent, et ses mots ont été mesurés et coupés à la largeur de la liste "
    "ci-dessus.",
    stamp="SPÉCIMEN",
    quoted_before="Chiffré en deux encres : ",
    quoted_between=" et ",
    quoted_after=", chacune sur sa plaque.",
)

# 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 ramp_caption(ink: str, after: str) -> str:
    """The caption over a ramp of tints: the ink it shows, then what it shows of it."""
    return f"{ink}{after}"


def quoted(words: Words) -> str:
    """The closing line, which names the two inks the work is quoted in."""
    return (
        f"{words.quoted_before}{BLUE}{words.quoted_between}{GOLD}"
        f"{words.quoted_after}"
    )


def tint_ramp(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    ink: hqf_pdf.ColorSpaceHandle,
    y: float,
    caption: str,
) -> None:
    """Draws the ten tints of one ink, each labelled with how much goes down."""
    width, height = TINT_SIZE

    for x, tint in zip(TINT_X, TINTS):
        content.save_state()
        content.set_fill_space(ink)
        content.set_fill_components([tint])
        content.rect(x, y, width, height)
        content.fill()
        content.restore_state()

        content.save_state()
        content.set_fill(hqf_pdf.Rgb.gray(0.35))
        content.draw_text(font, SWATCH_SIZE, x, y - 11.0, tint_name(tint))
        content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.2))
    content.draw_text(font, CAPTION_SIZE, LEFT, y + height + 8.0, caption)
    content.restore_state()


def registration(content: hqf_pdf.Content, x: float, y: float) -> None:
    """Draws a printer's crosshair centred on `(x, y)`, in the space in force."""
    arm = 7.0
    content.move_to(x - arm, y)
    content.line_to(x + arm, y)
    content.move_to(x, y - arm)
    content.line_to(x, y + arm)
    content.stroke()

    content.rect(x - 4.0, y - 4.0, 8.0, 8.0)
    content.stroke()


def sheet(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    words: Words,
    blue: hqf_pdf.ColorSpaceHandle,
    gold: hqf_pdf.ColorSpaceHandle,
    registration_ink: hqf_pdf.ColorSpaceHandle,
) -> None:
    """Draws a piece of work set in the two inks, with the marks a printer lines the
    plates up by around it."""
    bottom, height = 250.0, 190.0
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.75))
    content.set_line_width(0.5)
    content.rect(LEFT, bottom, WIDTH, height)
    content.stroke()
    content.restore_state()

    content.save_state()
    content.set_fill_space(blue)
    content.set_fill_components([1.0])
    content.draw_text(
        font, SHEET_TITLE_SIZE, LEFT + 24.0, bottom + 130.0, words.sheet_title
    )
    content.set_fill_components([PANEL_TINT])
    content.rect(LEFT + 24.0, bottom + 40.0, WIDTH - 48.0, 66.0)
    content.fill()
    content.restore_state()

    content.save_state()
    content.set_fill_space(gold)
    content.set_fill_components([1.0])
    content.rect(LEFT + 24.0, bottom + 118.0, 180.0, 3.0)
    content.fill()
    content.draw_text(
        font, SHEET_LINE_SIZE, LEFT + 40.0, bottom + 68.0, words.sheet_line
    )
    content.restore_state()

    content.save_state()
    content.set_stroke_space(registration_ink)
    content.set_stroke_components([1.0])
    content.set_line_width(0.5)
    for x, y in crosshairs(bottom, height):
        registration(content, x, y)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(font, MARK_SIZE, LEFT, bottom - 40.0, words.marks)
    content.restore_state()


def run_list(
    font: hqf_pdf.FontHandle,
    words: Words,
    blue: hqf_pdf.ColorSpaceHandle,
    gold: hqf_pdf.ColorSpaceHandle,
) -> hqf_pdf.Table:
    """The run list, set in the two inks and in nothing else.

    The heading stands on a full-strength plate of the first ink, every other line
    on an eight percent tint of it, the total on the second, and every rule in one
    or the other.
    """
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(54.0),
            hqf_pdf.ColumnWidth.points(74.0),
            hqf_pdf.ColumnWidth.points(66.0),
        ],
        WIDTH,
    )
    table = hqf_pdf.Table(columns)
    table.fill(hqf_pdf.Area.even_rows(), hqf_pdf.Paint.named(blue, [SHADED_TINT]))
    table.fill(hqf_pdf.Area.header(), hqf_pdf.Paint.named(blue, [1.0]))
    table.rule(
        hqf_pdf.Rule.frame(),
        hqf_pdf.Stroke(0.8, hqf_pdf.Paint.named(blue, [0.55])),
    )
    table.rule(
        hqf_pdf.Rule.horizontal_other(),
        hqf_pdf.Stroke(0.3, hqf_pdf.Paint.named(blue, [0.3])),
    )
    table.rule(
        hqf_pdf.Rule.horizontal(1),
        hqf_pdf.Stroke(1.2, hqf_pdf.Paint.named(gold, [1.0])),
    )
    table.header(1)

    def heading(label: str, align: hqf_pdf.Align) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            CELL_SIZE,
            label,
            align=align,
            valign=hqf_pdf.VAlign.Middle,
            color=hqf_pdf.Rgb.gray(1.0),
            padding=hqf_pdf.Padding.symmetric(6.0, 5.0),
        )

    item, sheets, plates, price = words.headings
    table.push(
        hqf_pdf.Row(
            [
                heading(item, hqf_pdf.Align.Left),
                heading(sheets, hqf_pdf.Align.Right),
                heading(plates, hqf_pdf.Align.Left),
                heading(price, hqf_pdf.Align.Right),
            ]
        )
    )

    def line(label: str, align: hqf_pdf.Align) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            CELL_SIZE,
            label,
            align=align,
            color=hqf_pdf.Paint.named(blue, [0.95]),
            padding=hqf_pdf.Padding.symmetric(6.0, 5.0),
        )

    for index, (sheets, plates, price) in enumerate(ITEMS):
        table.push(
            hqf_pdf.Row(
                [
                    line(words.items[index], hqf_pdf.Align.Left),
                    line(sheets, hqf_pdf.Align.Right),
                    line(plates.named(words), hqf_pdf.Align.Left),
                    line(price, hqf_pdf.Align.Right),
                ]
            )
        )

    def total(label: str, align: hqf_pdf.Align) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            TOTAL_SIZE,
            label,
            align=align,
            color=hqf_pdf.Paint.named(blue, [1.0]),
            padding=hqf_pdf.Padding.symmetric(6.0, 6.0),
        )

    table.push(
        hqf_pdf.Row(
            [
                total(words.total, hqf_pdf.Align.Left),
                total("", hqf_pdf.Align.Right),
                total("", hqf_pdf.Align.Left),
                total(TOTAL, hqf_pdf.Align.Right),
            ],
            fill=hqf_pdf.Paint.named(gold, [0.28]),
        )
    )
    return table


def run_sheet(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    words: Words,
    blue: hqf_pdf.ColorSpaceHandle,
    gold: hqf_pdf.ColorSpaceHandle,
) -> None:
    """Draws the run list, the note whose two runs each stand in the ink they
    name, and a specimen mark laid across the whole of it."""
    content.save_state()
    content.set_fill_space(blue)
    content.set_fill_components([1.0])
    content.draw_text(font, HEAD_SIZE, LEFT, HEAD_BASELINE, words.list_title)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    for line, y in zip(words.list_lead, LEAD_BASELINES):
        content.draw_text(font, LEAD_SIZE, LEFT, y, line)
    content.restore_state()

    table = run_list(font, words, blue, gold)
    placed = table.fit(LEFT, LIST_TOP, LIST_TOP - 260.0, 0)
    height = placed.height
    placed.draw(content)

    first_ink = hqf_pdf.Style(
        font, TOTAL_SIZE, color=hqf_pdf.Paint.named(blue, [PROSE_TINT])
    )
    second_ink = hqf_pdf.Style(
        font, TOTAL_SIZE, color=hqf_pdf.Paint.named(gold, [1.0])
    )
    note = hqf_pdf.RichText()
    note.span(words.note[0], first_ink)
    note.span(words.note[1], second_ink)
    note.span(words.note[2], first_ink)
    lines = note.break_lines(WIDTH)
    note_top = LIST_TOP - height - 26.0
    note.draw(content, lines, LEFT, note_top, WIDTH)

    flow = hqf_pdf.TextFlow(
        font,
        PROSE_SIZE,
        color=hqf_pdf.Paint.named(blue, [PROSE_TINT]),
        leading=PROSE_LEADING,
    )
    prose = flow.break_lines(words.prose, WIDTH)
    flow.draw(
        content,
        prose,
        LEFT,
        note_top - hqf_pdf.RichText.height(lines) - 26.0,
        WIDTH,
    )

    stamp = hqf_pdf.Stamp(
        font, words.stamp, color=hqf_pdf.Paint.named(gold, [0.22])
    )
    stamp.draw(content, LEFT, LIST_TOP - height, WIDTH, height)

    content.save_state()
    content.set_stroke_space(gold)
    content.set_stroke_components([1.0])
    content.set_line_width(0.8)
    content.move_to(LEFT, CLOSING_RULE)
    content.line_to(LEFT + WIDTH, CLOSING_RULE)
    content.stroke()
    content.set_fill_space(blue)
    content.set_fill_components([0.55])
    content.draw_text(
        font, CLOSING_SIZE, LEFT, CLOSING_RULE - 14.0, quoted(words)
    )
    content.restore_state()


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("spot.pdf", language)).stem)

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

    blue = document.add_color_space(
        hqf_pdf.Separation.ink(BLUE, hqf_pdf.Cmyk(0.92, 0.58, 0.0, 0.06))
    )
    gold = document.add_color_space(
        hqf_pdf.Separation.ink(GOLD, hqf_pdf.Cmyk(0.0, 0.28, 0.95, 0.04))
    )

    # The colorant every plate answers to: a mark set in it goes down on all of them,
    # which is how a printer sees whether they line up. It is shown as black where no
    # press is involved, so the tint transform runs from the paper to the ink.
    registration_ink = document.add_color_space(
        hqf_pdf.Separation(
            ALL_PLATES,
            hqf_pdf.DeviceSpace.Gray,
            hqf_pdf.Function.exponential(
                (0.0, 1.0), 1.0, endpoints=([1.0], [0.0]), range=[(0.0, 1.0)]
            ),
        )
    )

    content = hqf_pdf.Content()
    content.draw_text(font, HEAD_SIZE, LEFT, HEAD_BASELINE, words.title)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    for line, y in zip(words.lead, LEAD_BASELINES):
        content.draw_text(font, LEAD_SIZE, LEFT, y, line)
    content.restore_state()

    tint_ramp(content, font, blue, 640.0, ramp_caption(BLUE, words.first_ramp))
    tint_ramp(content, font, gold, 530.0, ramp_caption(GOLD, words.second_ramp))

    sheet(content, font, words, blue, gold, registration_ink)

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

    second = hqf_pdf.Content()
    run_sheet(second, font, words, blue, gold)
    page = hqf_pdf.Page.a4()
    page.set_content(second)
    document.add_page(page)

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, 2 pages, two inks at {len(TINTS)} "
        f"tints each, {len(ITEMS)} priced lines"
    )


if __name__ == "__main__":
    main()
