"""Writes a page of Aztec codes, drawn as squares.

The Python twin of the `write_aztec` example in Rust: the same page, through
the binding rather than through the library directly.

Whether an Aztec code works is not a question the page can answer, and not one
a human eye can: it is answered by a scanner. So the page carries what each
code says under it, and `scripts/check_aztec.sh` points a decoder at the
rendered image and compares.

An Aztec code needs no quiet zone: a scanner finds the bullseye at its centre
without one. The codes are still set apart from each other, so that one code's
modules are not read as another's.

The head of the sheet says what the squares are for, so that the page is worth
something to whoever opens it without the code beside it. Those words are held in
`Words`, once per language, and `HQF_PDF_LANG` picks which set the sheet is headed in.
What the codes carry stands apart from them: a scanner reads it, not a person, and it is
the same in every language.

A second column holds three more, each built another way: a text at the correction the
library chooses, bytes as they are, and bytes at a stated correction. Each says under its
payload how many layers it has, whether it is compact, and how many of its modules are
dark.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# What the codes carry, and how much of each is given over to error correction: a
# boarding pass at the share the standard advises, a tracking link at twice that, and a
# line of mixed punctuation at the least a code will take.
CARRIED = [
    ("HQF2026 PARIS LONDON 14B 07JUL", hqf_pdf.Aztec.default_correction()),
    ("https://example.test/track/FR-1964413", 46),
    ("a-Z 0..9 +*#% and on", 5),
]

# A text at the correction the library chooses when none is given.
PLAIN = "HQF AZTEC 2026"

# A payload handed over as bytes, as they are.
BYTES = "AZTEC BYTES"

# A payload handed over as bytes, at a stated correction.
LOT = "LOT 4472"

# Where the second column of codes stands.
SECOND_COLUMN = 330.0

# The side of one module, in points. Four pixels to a module at 288dpi, so every
# module's edge lands on a pixel boundary.
MODULE = 3.0

# The clear space left between one code and the next, in points.
GAP = 18.0

# How far to the right of a code its label is set, in points.
LABEL = 12.0

# Where the head of the first code sits, in points up from the foot of the sheet.
TOP = 700.0

# How far in from the left edge of the sheet the head of the page is set. The codes
# stand there too, so the heading stands over their left edge.
MARGIN = 72.0

# Where the baseline of the heading sits, in points up from the foot of the sheet.
HEAD_TOP = 794.0

# The size the heading is set at, in points.
HEADING = 16.0

# The size the lines under the heading are set at, in points.
BODY = 10.5

# How far under the heading the first line beneath it sits, in points.
HEAD_GAP = 24.0

# How far below one line under the heading the next one sits, in points.
LINE_STEP = 15.0

@dataclass(frozen=True)
class Words:
    """Every word the sheet is headed in, in one language."""

    # What the page says it is, at its head and in what the file says of itself.
    title: str
    # What the page says under its heading.
    lines: tuple[str, str]
    # The line under a code of the second column that says its shape; `{layers}`,
    # `{kind}` and `{dark}` stand for what is read back from it.
    shape: str
    # What a compact code and a full-range one are called.
    kinds: tuple[str, str]


# The head of the sheet in English.
ENGLISH = Words(
    title="Aztec codes, drawn as squares",
    lines=(
        (
            "An Aztec code asks for no white margin around it, so it fits where "
            "nothing else"
        ),
        "would; a train ticket carries one. Beside each is what a scanner reads back.",
    ),
    shape="{kind}, layers: {layers}, dark modules: {dark}",
    kinds=(
        "compact",
        "full-range",
    ),
)

# The sheet in French.
FRENCH = Words(
    title="Des codes Aztec, dessinés en carrés",
    lines=(
        (
            "Un code Aztec ne demande aucune marge blanche autour de lui : il tient là "
            "où rien"
        ),
        (
            "d’autre ne tiendrait. Un billet de train en comporte un. À côté, ce qu’un "
            "scanner y lit."
        ),
    ),
    shape="{kind}, couches : {layers}, modules sombres : {dark}",
    kinds=(
        "compact",
        "pleine taille",
    ),
)

# The sheet in Dutch.
DUTCH = Words(
    title="Aztec-codes, getekend als vierkantjes",
    lines=(
        (
            "Een Aztec-code vraagt geen witte rand, dus past hij waar niets anders zou"
        ),
        "passen; op een treinkaartje staat er een. Ernaast wat een scanner teruggeeft.",
    ),
    shape="{kind}, lagen: {layers}, donkere modules: {dark}",
    kinds=(
        "compact",
        "volledig bereik",
    ),
)

# The sheet in Portuguese.
PORTUGUESE = Words(
    title="Códigos Aztec, desenhados como quadrados",
    lines=(
        (
            "Um código Aztec não pede margem branca à volta, por isso cabe onde nada "
            "mais"
        ),
        "caberia; um bilhete de comboio leva um. Ao lado, o que um leitor lê nele.",
    ),
    shape="{kind}, camadas: {layers}, módulos escuros: {dark}",
    kinds=(
        "compacto",
        "completo",
    ),
)

# The sheet in Italian.
ITALIAN = Words(
    title="Codici Aztec, disegnati a quadrati",
    lines=(
        (
            "Un codice Aztec non chiede margine bianco intorno, così entra dove "
            "nient’altro"
        ),
        "entrerebbe; un biglietto del treno ne porta uno. Accanto, ciò che legge uno scanner.",
    ),
    shape="{kind}, strati: {layers}, moduli scuri: {dark}",
    kinds=(
        "compatto",
        "gamma completa",
    ),
)

# The sheet in Spanish.
SPANISH = Words(
    title="Códigos Aztec, dibujados como cuadrados",
    lines=(
        (
            "Un código Aztec no pide margen blanco alrededor, así que cabe donde nada "
            "más"
        ),
        "cabría; un billete de tren lleva uno. Al lado, lo que lee un escáner.",
    ),
    shape="{kind}, capas: {layers}, módulos oscuros: {dark}",
    kinds=(
        "compacto",
        "rango completo",
    ),
)

# The sheet in German.
GERMAN = Words(
    title="Aztec-Codes, als Quadrate gezeichnet",
    lines=(
        (
            "Ein Aztec-Code braucht keinen weißen Rand und passt, wo sonst nichts"
        ),
        "Platz hätte; eine Fahrkarte trägt einen. Daneben steht, was ein Scanner liest.",
    ),
    shape="{kind}, Lagen: {layers}, dunkle Module: {dark}",
    kinds=(
        "kompakt",
        "Vollformat",
    ),
)

# 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 head(content, handle, words) -> None:
    """Draw the heading, and the lines under it that say what the page is for."""
    content.draw_text(handle, HEADING, MARGIN, HEAD_TOP, words.title)

    y = HEAD_TOP - HEAD_GAP
    for line in words.lines:
        content.draw_text(handle, BODY, MARGIN, y, line)
        y -= LINE_STEP


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_info("Title", words.title)

    handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    content = hqf_pdf.Content()
    content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
    head(content, handle, words)

    # One code to a row, its label level with the middle of it, so no label runs into
    # the code or the label beside it.
    left = MARGIN
    top = TOP
    for carried, correction in CARRIED:
        code = hqf_pdf.Aztec(carried, correction=correction)
        side = code.size * MODULE
        bottom = top - side

        content.draw_aztec(code, left, bottom, side)
        content.draw_text(handle, 8.0, left + side + LABEL, bottom + side / 2.0, carried)

        top = bottom - GAP

    # A second column, each code built another way and read back for its shape: how many
    # layers it has, whether it is compact, and how many of its modules are dark.
    others = [
        (hqf_pdf.Aztec(PLAIN), PLAIN),
        (hqf_pdf.Aztec(BYTES.encode()), BYTES),
        (hqf_pdf.Aztec(LOT.encode(), correction=50), LOT),
    ]
    top = TOP
    for code, carried in others:
        size = code.size
        side = size * MODULE
        bottom = top - side
        content.draw_aztec(code, SECOND_COLUMN, bottom, side)
        dark = sum(
            1
            for row in range(size)
            for column in range(size)
            if code.is_dark(row, column)
        )
        shape = (
            words.shape.replace("{layers}", str(code.layers))
            .replace("{kind}", words.kinds[0 if code.compact else 1])
            .replace("{dark}", str(dark))
        )
        for line, lift in ((carried, 5.0), (shape, -6.0)):
            at = (SECOND_COLUMN + side + LABEL, bottom + side / 2.0 + lift)
            content.draw_text(handle, 8.0, at[0], at[1], line)
        top = bottom - GAP

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