"""Draws a delivery note: what left the warehouse, line by line, each article
carrying the barcode a scanner reads it back by, and a box the receiver ticks.

The Python twin of the `write_delivery_note` example in Rust. It shows a table put to
a use text alone cannot serve: every line's box is asked for by position, so a barcode
lands against its own article and a tick box against its own line. `Placement.row_top`
and `Placement.row_height` are what make that possible — the table decides the
geometry, and the page draws into it.

Whether the barcodes scan is not for the page to say, and not for an eye: a scanner
says. `scripts/check_barcode.sh` points a decoder at the rendered page and reads the
article numbers back.

Every word the page draws is held in `Words`, once per language, and `HQF_PDF_LANG`
picks which one is drawn. The article numbers, the quantities, the weight and the
numbers the note and the consignment answer to are the same in both, and so is what a
scanner reads off the page.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# A4, in points, and the page's left edge with its mirrored right.
PAGE_WIDTH = 595.276
PAGE_HEIGHT = 841.89
LEFT = 56.0
RIGHT = PAGE_WIDTH - LEFT
TABLE_WIDTH = PAGE_WIDTH - 2 * LEFT

# The ink the headings and rules are drawn in, and the grey of the small print.
ACCENT = hqf_pdf.Rgb(0.11, 0.33, 0.55)
MUTED = hqf_pdf.Rgb(0.42, 0.42, 0.45)
INK = hqf_pdf.Rgb(0.1, 0.1, 0.12)

# The logo the letterhead carries: the committed fixture, so the example runs on any
# machine. It stands in for the sender's mark.
LOGO = Path(__file__).resolve().parents[2] / "hqf-pdf" / "tests" / "images" / "hqf_development.png"

# The columns the table is cut into, in points. The description takes whatever the
# others leave it.
ARTICLE_WIDTH = 104.0
ORDERED_WIDTH = 52.0
DELIVERED_WIDTH = 56.0
RECEIVED_WIDTH = 58.0

# The width of the narrowest bar of an article's barcode, in points. An EAN-13 is 95 of
# them wide, and the quiet zone either side is ten more.
MODULE = 0.62
# How tall those bars are drawn, in points.
BAR_HEIGHT = 21.0


@dataclass(frozen=True)
class Line:
    """One line of the delivery note, apart from what the article is called: the figures
    read the same whatever language the page is set in.
    """

    article: str
    ordered: int
    delivered: int


# The lines this note delivers, in the order ``Words.labels`` names them. The fourth is
# short: the note says so rather than quietly billing what never left.
LINES = [
    Line("3760012844104", 12, 12),
    Line("3760012844272", 50, 50),
    Line("3760012844340", 8, 8),
    Line("3760012844418", 4, 2),
    Line("3760012844586", 12, 12),
    Line("3760012844654", 20, 20),
]

# What the note is called, the order it answers, and who carried the goods.
NUMBER = "DN-2026-0871"
ORDER = "PO-4471-NW"
CARRIER = "Northlight Express"
# The number the carrier tracks the consignment by, and which the code at the foot of
# the page carries.
CONSIGNMENT = "GX-2026-0871-004"

# How many parcels the consignment came to, and what they weigh together.
PARCELS = 4
WEIGHT = "38.4 kg"


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

    What is not language stays out of it: the article numbers, the quantities, the
    weight, the numbers the note and the consignment answer to, and the sender's and
    receiver's names and addresses are drawn from constants of their own and read the
    same in every language.
    """

    # The words the document's title is built from, and the words set large at the head
    # of the page.
    note: str
    heading: str
    # What stands before the note's own number, and before the order it answers.
    number_label: str
    order_label: str
    # What stands before the day the goods left, and that day as this language writes
    # it.
    shipped_label: str
    shipped_date: str
    # The heading over the receiver, and the line that sends the goods to the door that
    # takes them in.
    deliver_to: str
    goods_inwards: str
    # The heading over the carrier, and what the parcels are counted in.
    carried_by: str
    parcels: str
    # What each article is called, in the order ``LINES`` delivers them.
    labels: tuple[str, str, str, str, str, str]
    # The five column headings of the table.
    article: str
    description: str
    ordered: str
    delivered: str
    received: str
    # The heading over the foot of the page, and the two lines of small print under it.
    receipt: str
    terms_first: str
    terms_second: str
    # What each of the two signature lines is for.
    driver: str
    received_by: str
    # The word before the sender's tax number in the footer.
    vat: str


# The note in English.
ENGLISH = Words(
    note="Delivery note",
    heading="DELIVERY NOTE",
    number_label="Note No.",
    order_label="Your order",
    shipped_label="Shipped",
    shipped_date="20 July 2026",
    deliver_to="DELIVER TO",
    goods_inwards="Goods inwards",
    carried_by="CARRIED BY",
    parcels="parcels",
    labels=(
        "Rack server rail kit, 1U",
        "Patch cable Cat 6A, 2 m, grey",
        "SFP+ transceiver, 10G, multimode",
        "Fibre patch panel, 24 port",
        "Cable management arm",
        "Blanking panel, 1U, toolless",
    ),
    article="Article",
    description="Description",
    ordered="Ordered",
    delivered="Delivered",
    received="Received",
    receipt="RECEIPT",
    terms_first="Tick each line received, then sign. Damage or shortage must be noted",
    terms_second=(
        "here on delivery: a claim made later cannot be traced to the carrier."
    ),
    driver="Driver",
    received_by="Received by (name and date)",
    vat="VAT",
)

# The note in French.
FRENCH = Words(
    note="Bon de livraison",
    heading="BON DE LIVRAISON",
    number_label="Bon n°",
    order_label="Votre commande",
    shipped_label="Expédié le",
    shipped_date="20 juillet 2026",
    deliver_to="LIVRER À",
    goods_inwards="Service réception",
    carried_by="TRANSPORTEUR",
    parcels="colis",
    labels=(
        "Kit de rails pour serveur en baie, 1U",
        "Cordon de brassage Cat 6A, 2 m, gris",
        "Module SFP+ 10G, multimode",
        "Panneau de brassage fibre, 24 ports",
        "Bras de guidage des câbles",
        "Plastron d'obturation, 1U, sans outil",
    ),
    article="Article",
    description="Désignation",
    ordered="Qté cdée",
    delivered="Qté livrée",
    received="Reçu",
    receipt="RÉCEPTION",
    terms_first=(
        "Cochez chaque ligne reçue, puis signez. Toute avarie ou tout manquant doit"
    ),
    terms_second=(
        "être signalé ici à la livraison : une réserve tardive n'est plus "
        "opposable au transporteur."
    ),
    driver="Chauffeur",
    received_by="Reçu par (nom et date)",
    vat="TVA",
)


# 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 text(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    x: float,
    y: float,
    color: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text, left-aligned, in a colour of its own."""
    content.set_fill(color)
    content.draw_text(font, size, x, y, s)


def text_right(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    right: float,
    y: float,
    color: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text whose right edge sits at ``right``."""
    text(content, font, size, right - font.measure(s, size), y, color, s)


def text_centred(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    centre: float,
    y: float,
    color: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text centred on ``centre``."""
    text(content, font, size, centre - font.measure(s, size) / 2.0, y, color, s)


def rule(content: hqf_pdf.Content, y: float, width: float, color: hqf_pdf.Rgb) -> None:
    """A horizontal rule from ``LEFT`` to ``RIGHT`` at height ``y``."""
    content.set_stroke(color)
    content.set_line_width(width)
    content.move_to(LEFT, y)
    content.line_to(RIGHT, y)
    content.stroke()


def lines_table(font: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Table:
    """The note's table: a heading row, then one row per line delivered.

    The article column is left empty of everything but its digits: the barcode is drawn
    into the space above them once the table has said where the row sits. The rows are
    given a height that space needs.
    """
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.points(ARTICLE_WIDTH),
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(ORDERED_WIDTH),
            hqf_pdf.ColumnWidth.points(DELIVERED_WIDTH),
            hqf_pdf.ColumnWidth.points(RECEIVED_WIDTH),
        ],
        TABLE_WIDTH,
    )

    table = hqf_pdf.Table(columns)
    table.header(1)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8, ACCENT))
    table.rule(
        hqf_pdf.Rule.horizontal_other(), hqf_pdf.Stroke(0.25, hqf_pdf.Rgb.gray(0.78))
    )
    table.rule(
        hqf_pdf.Rule.vertical_other(), hqf_pdf.Stroke(0.25, hqf_pdf.Rgb.gray(0.85))
    )
    table.rule(hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.8, ACCENT))

    pad = hqf_pdf.Padding.symmetric(6.0, 5.0)
    white = hqf_pdf.Rgb.gray(1.0)

    def heading(label: str, align: hqf_pdf.Align = hqf_pdf.Align.Left) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            8.5,
            label,
            padding=pad,
            fill=ACCENT,
            color=white,
            align=align,
            valign=hqf_pdf.VAlign.Middle,
        )

    table.push(
        hqf_pdf.Row(
            [
                heading(words.article, hqf_pdf.Align.Center),
                heading(words.description),
                heading(words.ordered, hqf_pdf.Align.Right),
                heading(words.delivered, hqf_pdf.Align.Right),
                heading(words.received, hqf_pdf.Align.Center),
            ],
            min_height=22.0,
        )
    )

    for line, label in zip(LINES, words.labels):
        # A line delivered short is called out where the eye lands on it.
        short = line.delivered < line.ordered
        delivered_ink = hqf_pdf.Rgb(0.70, 0.18, 0.12) if short else INK

        table.push(
            hqf_pdf.Row(
                [
                    hqf_pdf.Cell(
                        font,
                        6.5,
                        line.article,
                        padding=pad,
                        align=hqf_pdf.Align.Center,
                        valign=hqf_pdf.VAlign.Bottom,
                    ),
                    hqf_pdf.Cell(
                        font, 9.0, label, padding=pad, valign=hqf_pdf.VAlign.Middle
                    ),
                    hqf_pdf.Cell(
                        font,
                        9.0,
                        str(line.ordered),
                        padding=pad,
                        align=hqf_pdf.Align.Right,
                        valign=hqf_pdf.VAlign.Middle,
                    ),
                    hqf_pdf.Cell(
                        font,
                        9.0,
                        str(line.delivered),
                        padding=pad,
                        align=hqf_pdf.Align.Right,
                        valign=hqf_pdf.VAlign.Middle,
                        color=delivered_ink,
                    ),
                    hqf_pdf.Cell(font, 9.0, "", padding=pad),
                ],
                min_height=44.0,
            )
        )

    return table


def marks_on_rows(
    content: hqf_pdf.Content,
    placed: hqf_pdf.Placement,
) -> None:
    """Draws each line's barcode above its article number, and the box the receiver
    ticks, into the rows the table has already placed.

    Row 0 is the heading, so the lines start at row 1. Asking the placement for a row it
    never placed gives nothing back, which is what stops the walk at the foot of the
    page.
    """
    # An EAN-13 is a fixed 95 modules wide, and the quiet zone the standard asks for
    # either side is ten more. The column holds all of it.
    bar_width = hqf_pdf.Ean13(LINES[0].article).module_count * MODULE
    bars_left = LEFT + (ARTICLE_WIDTH - bar_width) / 2.0
    tick_left = LEFT + TABLE_WIDTH - RECEIVED_WIDTH / 2.0 - 6.0

    for index, line in enumerate(LINES):
        top = placed.row_top(index + 1)
        height = placed.row_height(index + 1)
        if top is None or height is None:
            break
        bottom = top - height

        # The bars sit above the digits the cell drew, and the quiet zone either side of
        # them stays empty: the column is wide enough to hold both.
        content.set_fill(INK)
        code = hqf_pdf.Ean13(line.article)
        content.draw_ean13(code, bars_left, bottom + 15.0, bar_width, BAR_HEIGHT)

        # A box to tick, centred in its column and in the row.
        content.set_stroke(hqf_pdf.Rgb.gray(0.45))
        content.set_line_width(0.7)
        content.rect(tick_left, bottom + (height - 12.0) / 2.0, 12.0, 12.0)
        content.stroke()


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_info("Title", f"{words.note} {NUMBER}")

    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
    logo = document.add_image(hqf_pdf.Image.from_path(LOGO))

    content = hqf_pdf.Content()

    # The letterhead: the mark, the sender's name, what the page is, and the numbers it
    # answers to.
    logo_w, logo_h = logo.fit_within(84.0, 84.0)
    content.draw_image(logo, LEFT, 826.5 - logo_h, logo_w, logo_h)

    text(content, font, 8.5, LEFT, 768.0, MUTED, "42 lot les Genêts, 13480 Calas, France")
    text(content, font, 8.5, LEFT, 756.0, MUTED, "www.hqf.fr")

    text_right(content, font, 26.0, RIGHT, 796.0, ACCENT, words.heading)
    text_right(content, font, 9.5, RIGHT, 770.0, INK, f"{words.number_label}  {NUMBER}")
    text_right(content, font, 9.5, RIGHT, 757.0, MUTED, f"{words.order_label}  {ORDER}")
    text_right(
        content,
        font,
        9.5,
        RIGHT,
        744.0,
        MUTED,
        f"{words.shipped_label}  {words.shipped_date}",
    )

    rule(content, 730.0, 1.2, ACCENT)

    # Who the goods went to, and how they travelled.
    text(content, font, 8.0, LEFT, 712.0, MUTED, words.deliver_to)
    text(content, font, 11.0, LEFT, 697.0, INK, "Northwind Trading SARL")
    text(content, font, 9.0, LEFT, 683.0, MUTED, words.goods_inwards)
    text(content, font, 9.0, LEFT, 671.0, MUTED, "18 quai du Port")
    text(content, font, 9.0, LEFT, 659.0, MUTED, "13002 Marseille, France")

    text_right(content, font, 8.0, RIGHT, 712.0, MUTED, words.carried_by)
    text_right(content, font, 11.0, RIGHT, 697.0, INK, CARRIER)
    text_right(
        content, font, 9.0, RIGHT, 683.0, MUTED, f"{PARCELS} {words.parcels} · {WEIGHT}"
    )
    text_right(content, font, 9.0, RIGHT, 671.0, MUTED, CONSIGNMENT)

    # The lines, fitted onto this page, and then drawn into: the table settles the
    # geometry first so the barcodes and tick boxes know where to land.
    table = lines_table(font, words)
    table_top = 630.0
    placed = table.fit(LEFT, table_top, table_top - 250.0, 0)
    placed.draw(content)
    marks_on_rows(content, placed)
    table_bottom = table_top - placed.height

    # The foot of the page: the consignment's own code, what the receiver is agreeing
    # to, and the two lines they sign it on.
    top = table_bottom - 34.0
    text(content, font, 10.0, LEFT, top, ACCENT, words.receipt)
    text(content, font, 8.5, LEFT, top - 15.0, MUTED, words.terms_first)
    text(content, font, 8.5, LEFT, top - 26.0, MUTED, words.terms_second)

    # The consignment travels as one code, which is what the carrier scans at each
    # hand-over.
    code = hqf_pdf.Code128(CONSIGNMENT)
    module = 0.85
    width = code.module_count * module
    bars_left = RIGHT - width
    content.set_fill(INK)
    content.draw_barcode(code, bars_left, top + 2.0, width, 26.0)
    text_centred(content, font, 7.5, bars_left + width / 2.0, top - 8.0, MUTED, CONSIGNMENT)

    # Two lines to sign on, side by side, held down at the foot of the page rather than
    # under the words: that is where a hand reaches for them, and where the space left
    # for a note about damage ends up.
    sign_y = 150.0
    column = (TABLE_WIDTH - 40.0) / 2.0
    for offset, who in [(0.0, words.driver), (column + 40.0, words.received_by)]:
        x = LEFT + offset
        content.set_stroke(hqf_pdf.Rgb.gray(0.55))
        content.set_line_width(0.6)
        content.move_to(x, sign_y)
        content.line_to(x + column, sign_y)
        content.stroke()
        text(content, font, 8.0, x, sign_y - 11.0, MUTED, who)

    # The foot of the page: who sent the goods.
    rule(content, 74.0, 0.5, hqf_pdf.Rgb.gray(0.8))
    mentions = (
        "HQF Development · 42 lot les Genêts, 13480 Calas, France · "
        f"SIRET 752 492 777 00012 · APE 6202A · {words.vat} FR59 752 492 777"
    )
    text_centred(content, font, 7.0, LEFT + TABLE_WIDTH / 2.0, 62.0, MUTED, mentions)

    page = hqf_pdf.Page(PAGE_WIDTH, PAGE_HEIGHT)
    page.set_content(content)
    document.add_page(page)

    written = document.write(out)
    short = sum(line.ordered - line.delivered for line in LINES)
    print(f"wrote {out}: {written} bytes, {len(LINES)} lines, {short} short")


if __name__ == "__main__":
    main()
