"""Draws an airline boarding pass: the passenger and their flight, the route, the
times and the seat, a detachable stub down the side, and the code the gate scanner
reads.

The Python twin of the `write_boarding_pass` example in Rust. The code is not
decoration. It carries an IATA Resolution 792 bar coded boarding pass: one
fixed-width line, every field at its appointed offset, starting `M1` for a single
leg and running through the name, the booking reference, the two airports, the
carrier, the flight, the Julian day, the compartment, the seat, the check-in
sequence and the passenger status. A mobile pass carries that line as a
two-dimensional symbol, and this one carries it as a QR code.

Whether that code boards is not for the page to say, and not for an eye: a scanner
says. `scripts/check_qr.sh` points a decoder at the rendered page and reads the line
back.

Every word the page draws is held in `Words`, once per language, and `HQF_PDF_LANG`
picks which one is drawn. The passenger, the booking reference, the airports, the
flight, the times, the seat and the line the gate scanner reads are the same in both.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The card, in points: the width of an A4 sheet, a third of its height.
PAGE_WIDTH = 595.276
PAGE_HEIGHT = 283.465

# The card's left edge, the right edge of the part the passenger keeps, and the
# perforation the stub tears along.
LEFT = 24.0
MAIN_RIGHT = 416.0
PERFORATION = 430.0

# The stub's own left edge and, mirrored from the card, its right.
STUB_LEFT = 444.0
STUB_RIGHT = PAGE_WIDTH - LEFT

# The band across the head of the card, from this height to the top.
BAND_BOTTOM = PAGE_HEIGHT - 40.0

# The right edge of the column the fields are set in, left of the code.
FIELDS_RIGHT = 296.0

# The ink the airport codes and the head band are drawn in, the grey of the labels and
# the small print, and the near-black of the values.
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)

# Who is flying, and under which booking.
PASSENGER = "MOREAU/CLAIRE MS"
PNR = "K4RT9Z"

# The flight: where from, where to, whose aircraft, and which number. The carrier is the
# two-letter designator the operator files under.
FROM = "MRS"
TO = "LHR"
CARRIER = "HQ"
FLIGHT = "0421"

# The day of the flight, as the card writes it and as the code writes it: the ordinal
# day of the year, which is what Resolution 792 carries.
DATE = "20 JUL 2026"
JULIAN = "201"

# When boarding opens and when the aircraft leaves, and where to be.
BOARDING = "09:35"
DEPARTURE = "10:05"
GATE = "B14"

# The seat, its compartment, the order the passenger checked in, and whether they are
# checked in: status `1` is.
SEAT = "014A"
COMPARTMENT = "Y"
SEQUENCE = "0031"
STATUS = "1"


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

    What is not language stays out of it: the passenger, the booking reference, the
    airports, the flight, the times, the seat and the line the gate scanner reads 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 at the right of
    # the head band.
    title: str
    heading: str
    # The three fields across the top of the card, and what the last of them says.
    passenger: str
    booking_ref: str
    status_label: str
    status_value: str
    # What the two airports are called under their codes.
    from_name: str
    to_name: str
    # The eight field names down the card, and what the class field says.
    flight: str
    date: str
    boarding: str
    departs: str
    gate: str
    seat: str
    class_label: str
    class_value: str
    sequence: str
    # The two field names the stub adds for the route.
    from_label: str
    to_label: str
    # What stands under the code, and the notice at the foot of the card.
    caption: str
    notice: str
    # The two lines at the foot of the stub.
    retain_first: str
    retain_second: str


# The card in English.
ENGLISH = Words(
    title="Boarding pass",
    heading="BOARDING PASS",
    passenger="PASSENGER",
    booking_ref="BOOKING REF",
    status_label="STATUS",
    status_value="CHECKED IN",
    from_name="Marseille Provence",
    to_name="London Heathrow",
    flight="FLIGHT",
    date="DATE",
    boarding="BOARDING",
    departs="DEPARTS",
    gate="GATE",
    seat="SEAT",
    class_label="CLASS",
    class_value="ECONOMY",
    sequence="SEQ",
    from_label="FROM",
    to_label="TO",
    caption="IATA BCBP — scan at the gate",
    notice=(
        "Boarding closes 15 minutes before departure. Passport and this pass are "
        "asked for at the gate."
    ),
    retain_first="Please retain this stub",
    retain_second="until the end of the journey.",
)

# The card in French.
FRENCH = Words(
    title="Carte d'embarquement",
    heading="CARTE D'EMBARQUEMENT",
    passenger="PASSAGER",
    booking_ref="RÉSERVATION",
    status_label="STATUT",
    status_value="ENREGISTRÉ",
    from_name="Marseille Provence",
    to_name="Londres Heathrow",
    flight="VOL",
    date="DATE",
    boarding="EMBARQUEMENT",
    departs="DÉPART",
    gate="PORTE",
    seat="SIÈGE",
    class_label="CLASSE",
    class_value="ÉCONOMIE",
    sequence="SÉQ",
    from_label="DE",
    to_label="À",
    caption="IATA BCBP — à scanner à la porte",
    notice=(
        "L'embarquement ferme 15 minutes avant le départ. Une pièce d'identité et "
        "cette carte sont demandées à la porte."
    ),
    retain_first="Conservez ce talon",
    retain_second="jusqu'à la fin du voyage.",
)


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

# 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


def boarding_pass_code() -> str:
    """The line the code carries: an IATA Resolution 792 boarding pass, mandatory
    items only.

    Every field is fixed-width and padded with spaces to its size, because a reader
    takes each one by its offset and never looks for a separator: the name takes 20,
    the booking reference 7, each airport 3, the carrier 3, the flight number 5 —
    four digits and an operational suffix left blank — the Julian day 3, the
    compartment 1, the seat 4, the check-in sequence 5 and the passenger status 1.
    The two hex digits that close the line are the size of the conditional items that
    follow, and ``00`` says none do.
    """
    return (
        f"M1{PASSENGER:<20}E{PNR:<7}{FROM}{TO}{CARRIER:<3}{FLIGHT:<5}{JULIAN}"
        f"{COMPARTMENT}{SEAT}{SEQUENCE:<5}{STATUS}00"
    )


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 field(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    x: float,
    y: float,
    label: str,
    value: str,
    size: float,
) -> None:
    """One labelled field: its name above in small grey capitals, its value on the
    baseline ``y``.
    """
    text(content, font, 7.0, x, y + 14.0, MUTED, label)
    text(content, font, size, x, y, INK, value)


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


def band(content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words) -> None:
    """Draws the head band: the operator's mark across a filled strip, and the word
    the card is.
    """
    content.set_fill(ACCENT)
    content.rect(0.0, BAND_BOTTOM, PAGE_WIDTH, PAGE_HEIGHT - BAND_BOTTOM)
    content.fill()

    white = hqf_pdf.Rgb.gray(1.0)
    pale = hqf_pdf.Rgb.gray(0.85)
    text(content, font, 15.0, LEFT, 261.0, white, "HQF Development")
    text(content, font, 7.0, LEFT, 250.0, pale, "High Quality Foundations · www.hqf.fr")
    text_right(content, font, 15.0, STUB_RIGHT, 258.0, white, words.heading)


def perforation(content: hqf_pdf.Content) -> None:
    """Draws the tear line: the stub's tinted ground and the dashes the passenger
    tears along.
    """
    content.set_fill(hqf_pdf.Rgb.gray(0.96))
    content.rect(PERFORATION, 0.0, PAGE_WIDTH - PERFORATION, BAND_BOTTOM)
    content.fill()

    content.set_stroke(hqf_pdf.Rgb.gray(0.6))
    content.set_line_width(0.6)
    for index in range(28):
        y = 8.0 + index * 8.0
        content.move_to(PERFORATION, y)
        content.line_to(PERFORATION, y + 4.0)
    content.stroke()


def main_portion(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words
) -> None:
    """Draws the part the passenger shows at the gate: who, where to, when, and the
    scannable line.
    """
    field(content, font, LEFT, 210.0, words.passenger, PASSENGER, 13.0)
    field(content, font, 200.0, 210.0, words.booking_ref, PNR, 13.0)
    field(content, font, 300.0, 210.0, words.status_label, words.status_value, 13.0)
    rule(content, LEFT, MAIN_RIGHT, 198.0, 0.6, hqf_pdf.Rgb.gray(0.8))

    text(content, font, 30.0, LEFT, 166.0, ACCENT, FROM)
    text(content, font, 7.5, LEFT, 152.0, MUTED, words.from_name)
    text_right(content, font, 30.0, FIELDS_RIGHT, 166.0, ACCENT, TO)
    text_right(content, font, 7.5, FIELDS_RIGHT, 152.0, MUTED, words.to_name)
    arrow = "→"
    arrow_x = 165.0 - font.measure(arrow, 18.0) / 2.0
    text(content, font, 18.0, arrow_x, 166.0, ACCENT, arrow)
    rule(content, LEFT, FIELDS_RIGHT, 140.0, 0.6, hqf_pdf.Rgb.gray(0.8))

    flight = f"{CARRIER} {FLIGHT}"
    field(content, font, LEFT, 112.0, words.flight, flight, 9.5)
    field(content, font, 92.0, 112.0, words.date, DATE, 9.5)
    field(content, font, 170.0, 112.0, words.boarding, BOARDING, 9.5)
    field(content, font, 232.0, 112.0, words.departs, DEPARTURE, 9.5)

    field(content, font, LEFT, 72.0, words.gate, GATE, 9.5)
    field(content, font, 92.0, 72.0, words.seat, SEAT, 9.5)
    field(content, font, 170.0, 72.0, words.class_label, words.class_value, 9.5)
    field(content, font, 232.0, 72.0, words.sequence, SEQUENCE, 9.5)

    # The code sits at the right of this part, drawn as a square from its lower-left
    # corner. Nothing is drawn within its quiet zone, which is the caller's to leave:
    # the fields stop at FIELDS_RIGHT and the tear line stands off to the right of it.
    code = hqf_pdf.QrCode(boarding_pass_code())
    side = code.size * MODULE
    code_x = MAIN_RIGHT - side
    code_bottom = 46.0
    content.set_fill(hqf_pdf.Rgb.gray(0.0))
    content.draw_qr(code, code_x, code_bottom, side)
    text(
        content,
        font,
        6.5,
        code_x + (side - font.measure(words.caption, 6.5)) / 2.0,
        code_bottom - 14.0,
        MUTED,
        words.caption,
    )

    text(content, font, 6.5, LEFT, 20.0, MUTED, words.notice)


def stub(content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words) -> None:
    """Draws the stub the passenger tears off and keeps: the same flight, said again
    in the width of a thumb.
    """
    pair = STUB_LEFT + 64.0
    field(content, font, STUB_LEFT, 208.0, words.passenger, PASSENGER, 9.0)
    flight = f"{CARRIER} {FLIGHT}"
    field(content, font, STUB_LEFT, 174.0, words.flight, flight, 9.0)
    field(content, font, pair, 174.0, words.date, DATE, 8.0)
    field(content, font, STUB_LEFT, 140.0, words.from_label, FROM, 9.0)
    field(content, font, pair, 140.0, words.to_label, TO, 9.0)
    field(content, font, STUB_LEFT, 106.0, words.gate, GATE, 9.0)
    field(content, font, pair, 106.0, words.seat, SEAT, 9.0)
    field(content, font, STUB_LEFT, 72.0, words.class_label, words.class_value, 9.0)
    field(content, font, pair, 72.0, words.sequence, SEQUENCE, 9.0)

    text(content, font, 6.5, STUB_LEFT, 40.0, MUTED, words.retain_first)
    text(content, font, 6.5, STUB_LEFT, 30.0, MUTED, words.retain_second)


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

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_info("Title", f"{words.title} {CARRIER} {FLIGHT}")

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

    content = hqf_pdf.Content()
    band(content, font, words)
    perforation(content)
    main_portion(content, font, words)
    stub(content, font, words)

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

    written = document.write(out)
    print(f"wrote {out}: {written} bytes, {CARRIER} {FLIGHT} {FROM}–{TO} seat {SEAT}")


if __name__ == "__main__":
    main()
