"""Creates the receipt a shop's till prints on a roll: the shop at the head, the
basket line by line, the tax gathered by rate, what was handed over and what was
handed back, and the ticket's own barcode at the foot.

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

The roll is 80 mm across, which is the paper a counter printer takes, and the page is
as long as this basket makes it. Every figure on it is worked out rather than written
down: a line comes to its quantity times its unit price, the tax at each rate is taken
out of the gross that carries it, the total is the sum of the lines, and the change is
what is left of the note handed over.

The barcode is what the shop scans when the ticket comes back — a return, an exchange,
a warranty claim. `Code128.automatic` reads the number and picks the code set for it: a
ticket number of nothing but digits goes into code set C, two digits to a symbol, and
takes 112 modules where code set B would spell it out over 189.

Whether that barcode scans 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
number back.

Every word the ticket prints is held in `Words`, once per language, and `HQF_PDF_LANG`
picks which one it is printed in. What is not language stays out of it: the shop, the
date, the till, the amounts, the rates and the ticket number read the same whichever
set of words is drawn.

Usage: python examples/write_till_receipt.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_till_receipt.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 space that holds an amount and what stands beside it together.
NO_BREAK = " "

# The roll, in points: 80 mm across, cut long enough for this basket.
PAGE_WIDTH = 226.772
PAGE_HEIGHT = 486.0

# The margins the printer keeps clear, and the middle a centred line sits on.
LEFT = 14.0
RIGHT = PAGE_WIDTH - LEFT
CENTRE = PAGE_WIDTH / 2.0

# Where the first baseline sits, in points down from the top of the roll.
HEAD_TOP = 24.0

# The steps the ticket comes down the roll by: between two lines of a block, between two
# blocks, from one article to the next, and from an article to the quantity line under
# it.
LINE = 10.0
BLOCK = 13.0
ITEM = 20.0
SUB = 8.0

# The sizes the ticket is set at: the shop's name, the small print, the body of the
# basket, the line the ticket ends on, and the total.
SHOP_SIZE = 13.0
SMALL = 6.5
BODY = 8.0
THANKS_SIZE = 7.5
TOTAL_SIZE = 11.0

# The near-black a till prints in, and the grey the labels and the small print are set
# in.
INK = hqf_pdf.Rgb(0.1, 0.1, 0.12)
MUTED = hqf_pdf.Rgb(0.42, 0.42, 0.45)

# The shop: its name, where it stands, what to ring, and the number it is registered for
# tax under. It is the same shop whichever language the ticket is printed in.
SHOP = "Comptoir Vaugelade"
ADDRESS = "18 rue des Trois-Fontaines"
TOWN = "13290 Les Milles"
PHONE = "+33 4 42 00 71 30"
REGISTRATION = "FR 41 802 337 190"

# When the basket was rung up, at which till, and by whom.
DATE = "2026-08-31"
TIME = "18:42"
TILL = "04"
CASHIER = "Naïma"

# The ticket's own number: the till, the day, and the basket's place in the day. Nothing
# but digits, which is what sends it into code set C.
TICKET = "04202608310731"

# The currency every amount on the ticket is in.
CURRENCY = "EUR"

# What was handed over, in cents.
TENDERED = 6000

# The width of the narrowest bar, in points. Everything else is a whole number of these.
MODULE = 1.0

# How tall the bars are drawn, in points.
BAR_HEIGHT = 34.0

# The right edge of two of the three columns of figures in the tax table. The third ends
# at the right margin, and the rate is set from the left one.
NET_RIGHT = 120.0
TAX_RIGHT = 166.0


@dataclass(frozen=True)
class Rate:
    """A rate of tax: the reduced rate a grocer charges on food, and the standard rate
    on everything else.
    """

    # The rate itself, in tenths of a percent.
    tenths: int
    # The letter the ticket marks a line with, and the tax table names.
    letter: str

    def shown(self) -> str:
        """The rate as the ticket writes it: a point before the tenth, and a no-break
        space before the sign.
        """
        return f"{self.tenths // 10}.{self.tenths % 10}{NO_BREAK}%"


REDUCED = Rate(tenths=55, letter="A")
STANDARD = Rate(tenths=200, letter="B")

# Both rates, in the order the tax table sets them out.
RATES = (REDUCED, STANDARD)


@dataclass(frozen=True)
class Article:
    """One line of the basket: how many were scanned, what one of them costs in cents,
    and the rate of tax it carries.

    What the article is called is a word, and is held in `Words` at the place the line
    has here.
    """

    # How many of it were scanned.
    quantity: int
    # What one of them costs, in cents.
    unit: int
    # The rate of tax it carries.
    rate: Rate


# The basket, in the order it was scanned.
BASKET = (
    Article(quantity=1, unit=120, rate=REDUCED),
    Article(quantity=2, unit=890, rate=REDUCED),
    Article(quantity=3, unit=105, rate=REDUCED),
    Article(quantity=1, unit=1240, rate=REDUCED),
    Article(quantity=1, unit=675, rate=STANDARD),
    Article(quantity=1, unit=995, rate=STANDARD),
)


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

    What is not language stays out of it: the shop, its address, the date, the till,
    the cashier, the amounts, the rates and the ticket number are drawn from constants
    of their own and read the same in every language.
    """

    # What the file says it is, and the line under the shop's name.
    title: str
    tagline: str
    # What the shop's tax registration stands under.
    registration: str
    # The five marks at the head of the ticket.
    date: str
    time: str
    till: str
    served: str
    receipt: str
    # The two column heads over the basket.
    item: str
    amount: str
    # The six articles, in the order the basket holds them.
    articles: tuple[str, str, str, str, str, str]
    # The line that adds the basket up before tax, and the four column heads of the tax
    # table.
    net_total: str
    rate: str
    net: str
    tax: str
    gross: str
    # What the ticket comes to, what was handed over, what was handed back, and how many
    # articles were sold.
    total: str
    cash: str
    change: str
    count: str
    # The two lines under the barcode.
    keep: str
    thanks: str


# The ticket in English.
ENGLISH = Words(
    title="Till receipt",
    tagline="Grocer and general store",
    registration="VAT no.",
    date="DATE",
    time="TIME",
    till="TILL",
    served="SERVED BY",
    receipt="RECEIPT",
    item="ITEM",
    amount="AMOUNT",
    articles=(
        "Sourdough loaf",
        "Coffee beans 1 kg",
        "Whole milk 1 L",
        "Olive oil 75 cl",
        "Washing powder 2 kg",
        "Batteries AA, 8",
    ),
    net_total="TOTAL BEFORE TAX",
    rate="RATE",
    net="NET",
    tax="TAX",
    gross="GROSS",
    total="TOTAL",
    cash="CASH",
    change="CHANGE",
    count="ARTICLES SOLD",
    keep="Keep this ticket for any return or exchange.",
    thanks="Thank you for your visit — see you soon",
)

# The ticket in French.
FRENCH = Words(
    title="Ticket de caisse",
    tagline="Épicerie et bazar",
    registration="TVA n°",
    date="DATE",
    time="HEURE",
    till="CAISSE",
    served="SERVI PAR",
    receipt="TICKET",
    item="ARTICLE",
    amount="MONTANT",
    articles=(
        "Pain au levain",
        "Café en grains 1 kg",
        "Lait entier 1 L",
        "Huile d'olive 75 cl",
        "Lessive en poudre 2 kg",
        "Piles AA, 8",
    ),
    net_total="TOTAL HORS TAXE",
    rate="TAUX",
    net="HT",
    tax="TVA",
    gross="TTC",
    total="TOTAL",
    cash="ESPÈCES",
    change="RENDU",
    count="ARTICLES VENDUS",
    keep="Conservez ce ticket pour tout retour ou échange.",
    thanks="Merci de votre visite — à bientôt",
)

# 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 money(cents: int) -> str:
    """An amount of cents, its thousands parted by a no-break space and its decimals by
    a point, which is how every language this example is written in writes one.

    The currency is named once at the head of the column of amounts and once on the
    line of the total; the figures themselves are bare, as a till prints them.
    """
    whole, fraction = divmod(cents, 100)
    digits = str(whole)
    out = []
    for index, digit in enumerate(digits):
        if index > 0 and (len(digits) - index) % 3 == 0:
            out.append(NO_BREAK)
        out.append(digit)
    return f"{''.join(out)}.{fraction:02d}"


def line_total(article: Article) -> int:
    """What one line of the basket comes to, in cents."""
    return article.quantity * article.unit


def total() -> int:
    """What the whole basket comes to, in cents."""
    return sum(line_total(article) for article in BASKET)


def sold() -> int:
    """How many articles were sold, all lines together."""
    return sum(article.quantity for article in BASKET)


def gross_at(rate: Rate) -> int:
    """What the lines carrying ``rate`` come to, in cents, tax included."""
    return sum(line_total(article) for article in BASKET if article.rate == rate)


def tax_of(gross: int, rate: Rate) -> int:
    """What ``gross`` holds of tax at ``rate``, in cents, rounded to the nearest cent.

    The prices a shop shows already carry their tax, so the tax is taken out of the
    gross rather than added to a net: at a rate of ``t`` tenths of a percent, it is
    ``gross × t / (1000 + t)``.
    """
    denominator = 1000 + rate.tenths
    return (gross * rate.tenths * 2 + denominator) // (denominator * 2)


def ticket_code() -> hqf_pdf.Code128:
    """The bars the ticket carries.

    The number is nothing but digits, so ``automatic`` takes code set C for it and
    draws it in a little over half the bars code set B would spell it out in.
    """
    return hqf_pdf.Code128.automatic(TICKET)


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_centre(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    y: float,
    color: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text set across the middle of the roll."""
    text(content, font, size, CENTRE - font.measure(s, size) / 2.0, y, color, s)


def row(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    y: float,
    color: hqf_pdf.Rgb,
    left: str,
    right: str,
) -> None:
    """Draws a row with something at the left margin and something at the right."""
    text(content, font, size, LEFT, y, color, left)
    text_right(content, font, size, RIGHT, y, color, right)


def dashes(content: hqf_pdf.Content, y: float) -> None:
    """Draws the row of dashes a till prints between the parts of a ticket."""
    content.set_stroke(MUTED)
    content.set_line_width(0.5)
    content.set_dash(hqf_pdf.Dash.on_off(2.0, 2.0))
    content.move_to(LEFT, y)
    content.line_to(RIGHT, y)
    content.stroke()
    content.set_solid()


def head(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws the shop at the head of the roll, and hands back the baseline it ends
    on.
    """
    y = top
    text_centre(content, font, SHOP_SIZE, y, INK, SHOP)
    y -= 12.0
    text_centre(content, font, SMALL, y, MUTED, words.tagline)
    y -= LINE
    text_centre(content, font, SMALL, y, INK, ADDRESS)
    y -= SUB
    text_centre(content, font, SMALL, y, INK, TOWN)
    y -= SUB
    text_centre(content, font, SMALL, y, INK, PHONE)
    y -= SUB
    text_centre(content, font, SMALL, y, MUTED, f"{words.registration} {REGISTRATION}")
    return y


def marks(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws when the basket was rung up, at which till, by whom and under which
    number, and hands back the baseline it ends on.
    """
    y = top
    row(
        content,
        font,
        SMALL,
        y,
        INK,
        f"{words.date} {DATE}",
        f"{words.time} {TIME}",
    )
    y -= LINE
    row(
        content,
        font,
        SMALL,
        y,
        INK,
        f"{words.till} {TILL}",
        f"{words.served} {CASHIER}",
    )
    y -= LINE
    row(content, font, SMALL, y, INK, words.receipt, TICKET)
    return y


def basket(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws the basket, one article to two lines: what it is against what it came to,
    and under that how many at what price and which rate it carries. Hands back the
    baseline it ends on.
    """
    y = top
    for article, name in zip(BASKET, words.articles):
        row(content, font, BODY, y, INK, name, money(line_total(article)))

        counted = f"{article.quantity} × {money(article.unit)}"
        text(content, font, SMALL, LEFT + SUB, y - SUB, MUTED, counted)
        text_right(content, font, SMALL, RIGHT, y - SUB, MUTED, article.rate.letter)
        y -= ITEM
    return y + ITEM - SUB


def taxes(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws what the basket comes to before tax and the tax gathered by rate, and
    hands back the baseline it ends on.
    """
    y = top
    before_tax = sum(gross_at(rate) - tax_of(gross_at(rate), rate) for rate in RATES)
    row(content, font, BODY, y, INK, words.net_total, money(before_tax))

    y -= BLOCK
    text(content, font, SMALL, LEFT, y, MUTED, words.rate)
    text_right(content, font, SMALL, NET_RIGHT, y, MUTED, words.net)
    text_right(content, font, SMALL, TAX_RIGHT, y, MUTED, words.tax)
    text_right(content, font, SMALL, RIGHT, y, MUTED, words.gross)

    for rate in RATES:
        y -= LINE
        gross = gross_at(rate)
        tax = tax_of(gross, rate)
        text(content, font, SMALL, LEFT, y, INK, f"{rate.letter} {rate.shown()}")
        text_right(content, font, SMALL, NET_RIGHT, y, INK, money(gross - tax))
        text_right(content, font, SMALL, TAX_RIGHT, y, INK, money(tax))
        text_right(content, font, SMALL, RIGHT, y, INK, money(gross))
    return y


def settlement(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws what the ticket came to, what was handed over and what was handed back,
    and hands back the baseline it ends on.
    """
    y = top
    due = total()
    paid = f"{money(due)}{NO_BREAK}{CURRENCY}"
    row(content, font, TOTAL_SIZE, y, INK, words.total, paid)

    y -= BLOCK
    row(content, font, BODY, y, INK, words.cash, money(TENDERED))
    y -= LINE
    row(content, font, BODY, y, INK, words.change, money(TENDERED - due))
    y -= LINE
    row(content, font, SMALL, y, MUTED, words.count, str(sold()))
    return y


def foot(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws the ticket's own barcode and the two lines under it, and hands back the
    baseline it ends on.
    """
    code = ticket_code()
    width = code.module_count * MODULE

    # The quiet zone is the caller's: nothing else is drawn beside the bars, and the
    # roll leaves far more than the ten modules a scanner needs.
    y = top - BAR_HEIGHT
    content.set_fill(hqf_pdf.Rgb.gray(0.0))
    content.draw_barcode(code, (PAGE_WIDTH - width) / 2.0, y, width, BAR_HEIGHT)

    y -= LINE
    text_centre(content, font, SMALL, y, INK, TICKET)
    y -= LINE
    text_centre(content, font, SMALL, y, MUTED, words.keep)
    y -= 12.0
    text_centre(content, font, THANKS_SIZE, y, INK, words.thanks)
    return y


def ticket(content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words) -> float:
    """Draws the whole ticket, and hands back the baseline it ends on."""
    y = head(content, font, words, PAGE_HEIGHT - HEAD_TOP)

    y -= BLOCK
    dashes(content, y)
    y = marks(content, font, words, y - BLOCK)

    y -= BLOCK
    dashes(content, y)
    y -= BLOCK
    row(
        content,
        font,
        SMALL,
        y,
        MUTED,
        words.item,
        f"{words.amount}{NO_BREAK}{CURRENCY}",
    )
    y = basket(content, font, words, y - 12.0)

    y -= BLOCK
    dashes(content, y)
    y = taxes(content, font, words, y - BLOCK)

    y -= BLOCK
    dashes(content, y)
    y = settlement(content, font, words, y - 16.0)

    return foot(content, font, words, y - 18.0)


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

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

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

    content = hqf_pdf.Content()
    ticket(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, ticket {TICKET}, {sold()} articles, "
        f"{money(total())}{NO_BREAK}{CURRENCY}"
    )


if __name__ == "__main__":
    main()
