"""Writes a monthly payslip: a letterhead, the employee it names, an earnings table,
a dense table of contributions, and the cumulative figures a payslip carries.

The Python twin of the `write_payslip` example in Rust. The document is a table
before it is anything else: every contribution line is a base, a rate for the
employee and a rate for the employer, and the amount each rate comes to; the section
headings are rows that span the whole grid; and the totals are boxed off it. Every
figure on the page is worked out from the earnings above it, so the sums can be
checked with a pencil.

The file says what the page is made of, not only what it looks like: here is the
title, here is the table of the month's lines, here are its column headings and the
line each figure stands on. Each figure is tied to its line heading and its column
heading, the two a program reading the page aloud is given to announce it by. The mark
says in words what it shows, and the rules drawn across the page are marked as layout,
outside what the page says. The document claims PDF/UA-1.

Every word the page draws is held in `Words`, once per language, and `HQF_PDF_LANG`
picks which one is drawn. The figures, the rates, the ceiling and the employee's name
and staff number are the same in both.

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

from __future__ import annotations

import math
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 employer's mark.
LOGO = Path(__file__).resolve().parents[2] / "hqf-pdf" / "tests" / "images" / "hqf_development.png"

# When the payslip was drawn up: the day the pay was transferred. The library never
# reads the clock, so the file is the same on every build.
DRAWN_UP = "2026-07-31T09:30:00+02:00"

# Who the payslip is for.
EMPLOYEE_NAME = "Marion Delacroix"
EMPLOYEE_ID = "EMP-0231"

# What a quantity of one is counted in: hours, days, or nothing at all, in which case
# the quantity stands on its own.
HOUR = "hour"
DAY = "day"
BARE = "bare"


@dataclass(frozen=True)
class Earning:
    """One line of pay, apart from what it is called: a quantity of ``unit``, each worth
    ``unit_rate``. The figures read the same whatever language the page is set in.
    """

    quantity: float
    unit: str
    unit_rate: float


# What the month pays, before anything is taken off it, in the order ``Words.earnings``
# names them.
EARNINGS = [
    Earning(151.67, HOUR, 27.0),
    Earning(6.0, HOUR, 33.75),
    Earning(5.0, DAY, 40.0),
    Earning(1.0, BARE, 150.0),
]

# Which figure a contribution is worked out from: the whole of the gross pay, gross pay
# as far as the monthly social security ceiling, the part above that ceiling, or the
# part social surcharges are levied on.
GROSS = "gross"
CAPPED = "capped"
UPPER_BAND = "upper band"
SURCHARGE = "surcharge"


@dataclass(frozen=True)
class Section:
    """A heading over the contributions that follow it."""


@dataclass(frozen=True)
class Charge:
    """A contribution, in percent of its base, apart from what it is called.

    ``deducted`` is the rate taken out of the employee's pay and ``charged`` the rate
    the employer pays on top. ``non_deductible`` says whether the employee's share
    stays inside taxable pay.
    """

    base: str
    deducted: float
    charged: float
    non_deductible: bool = False


# The contributions the month is charged, in the order ``Words.lines`` names them.
LINES = [
    Section(),
    Charge(GROSS, 0.0, 7.0),
    Charge(GROSS, 0.75, 1.25),
    Charge(GROSS, 0.5, 0.0),
    Section(),
    Charge(CAPPED, 6.9, 8.55),
    Charge(GROSS, 0.4, 1.9),
    Charge(CAPPED, 3.15, 4.72),
    Charge(UPPER_BAND, 8.64, 12.95),
    Charge(CAPPED, 0.86, 1.29),
    Charge(UPPER_BAND, 1.08, 1.62),
    Section(),
    Charge(GROSS, 0.0, 5.25),
    Charge(GROSS, 0.0, 4.05),
    Charge(GROSS, 0.0, 0.15),
    Section(),
    Charge(GROSS, 0.0, 1.1),
    Charge(GROSS, 0.0, 0.3),
    Charge(GROSS, 0.0, 0.68),
    Charge(GROSS, 0.0, 1.0),
    Section(),
    Charge(SURCHARGE, 6.8, 0.0),
    Charge(SURCHARGE, 2.9, 0.0, non_deductible=True),
]

# The monthly social security ceiling the capped and upper bands are cut at, the share
# of gross pay the social surcharges are levied on, and the rate income tax is withheld
# at, as told to the employer by the revenue.
CEILING = 3925.0
SURCHARGE_SHARE = 0.9825
TAX_RATE = 11.2

# How many months of the year the cumulative column adds up, this one included. Every
# month of the year runs to the same figures.
MONTHS = 7.0

# The paid leave the employee stands at, in days.
LEAVE_EARNED = 27.5
LEAVE_TAKEN = 12.0


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

    What is not language stays out of it: the figures, the rates, the ceiling and the
    employee's name and staff number are drawn from constants of their own and read the
    same in every language.
    """

    # The BCP 47 tag the document states, and the words the file gives in place of the
    # mark at the head of the letterhead.
    lang: str
    logo_alt: str
    # The words the document's title is built from, the month it covers, and the word
    # set large at the head of the page.
    payslip: str
    month: str
    heading: str
    # What stands before the month the page covers, and that month written out as this
    # language writes a span of days.
    period_label: str
    period: str
    # What stands before the day the pay was transferred, and that day.
    paid_label: str
    pay_date: str
    # The heading over the employee, what the employee does, and what stands before the
    # staff number and before the day they joined.
    employee: str
    role: str
    staff_label: str
    joined_label: str
    joined_date: str
    # The heading over what is paid, and the line under the figure.
    net_paid: str
    transferred: str
    # What an hour and a day are written as after a quantity.
    hour: str
    day: str
    # The four column headings of the earnings table.
    earnings_heading: str
    quantity: str
    unit_rate: str
    earnings_amount: str
    # What each line of pay is called, in the order ``EARNINGS`` pays them, and the
    # total under them.
    earnings: tuple[str, str, str, str]
    gross_pay: str
    # The two tiers of headings of the contributions table.
    employee_share: str
    employer_share: str
    contribution: str
    base: str
    rate: str
    amount: str
    # What each row of the contributions table is called, in the order ``LINES`` sets
    # them, headings included.
    lines: tuple[str, ...]
    # The three totals under the contributions.
    total_contributions: str
    net_before_tax: str
    total_cost: str
    # The three column headings of the cumulative table, the five lines it carries, and
    # what is paid over at the foot of it.
    summary: str
    this_month: str
    year_to_date: str
    summary_lines: tuple[str, str, str, str, str]
    net_paid_row: str
    # The heading over the leave, and the three counts under it.
    leave: str
    leave_earned: str
    leave_taken: str
    leave_remaining: str
    # The working week, and the small print at the foot of the page.
    working_time: str
    mentions: str

    def unit(self, unit: str) -> str:
        """What a quantity is counted in, in this language."""
        if unit == HOUR:
            return self.hour
        if unit == DAY:
            return self.day
        return ""


# The payslip in English.
ENGLISH = Words(
    lang="en-GB",
    logo_alt="The HQF Development mark",
    payslip="Payslip",
    month="July 2026",
    heading="PAYSLIP",
    period_label="Period",
    period="1 – 31 July 2026",
    paid_label="Paid on",
    pay_date="31 July 2026",
    employee="EMPLOYEE",
    role="Senior software engineer — grade 3.2",
    staff_label="Staff No.",
    joined_label="Joined",
    joined_date="4 September 2023",
    net_paid="NET PAID",
    transferred="Transferred to the account on file",
    hour="h",
    day="d",
    earnings_heading="Earnings",
    quantity="Quantity",
    unit_rate="Unit rate",
    earnings_amount="Amount",
    earnings=(
        "Monthly base salary",
        "Overtime, first eight hours (125 %)",
        "On-call cover, weekend",
        "Seniority bonus",
    ),
    gross_pay="GROSS PAY",
    employee_share="Employee share",
    employer_share="Employer share",
    contribution="Contribution",
    base="Base",
    rate="Rate",
    amount="Amount",
    lines=(
        "HEALTH, MATERNITY, DISABILITY, DEATH",
        "Health and maternity insurance",
        "Supplementary health cover",
        "Daily sickness allowance",
        "RETIREMENT",
        "State pension, capped",
        "State pension, uncapped",
        "Supplementary pension, band 1",
        "Supplementary pension, band 2",
        "Balancing contribution, band 1",
        "Balancing contribution, band 2",
        "FAMILY AND UNEMPLOYMENT",
        "Family allowances",
        "Unemployment insurance",
        "Wage guarantee scheme",
        "OTHER EMPLOYER CONTRIBUTIONS",
        "Workplace accident cover",
        "Autonomy solidarity contribution",
        "Apprenticeship levy",
        "Continuing training levy",
        "SOCIAL SURCHARGES",
        "Social surcharge, deductible",
        "Social surcharge and debt levy, non-deductible",
    ),
    total_contributions="TOTAL CONTRIBUTIONS",
    net_before_tax="NET PAY BEFORE INCOME TAX",
    total_cost="TOTAL COST OF THE MONTH TO THE EMPLOYER",
    summary="Summary",
    this_month="This month",
    year_to_date="Year to date",
    summary_lines=(
        "Gross pay",
        "Employee contributions",
        "Employer contributions",
        "Taxable pay",
        "Income tax withheld at 11.20 %",
    ),
    net_paid_row="NET PAID",
    leave="PAID LEAVE",
    leave_earned="Earned this year",
    leave_taken="taken",
    leave_remaining="remaining",
    working_time="Working time: 35 h a week",
    mentions=(
        "Keep this payslip without limit of time · HQF Development · "
        "42 lot les Genêts, 13480 Calas, France · SIRET 752 492 777 00012 · APE 6202A"
    ),
)

# The payslip in French.
FRENCH = Words(
    lang="fr-FR",
    logo_alt="Le logo de HQF Development",
    payslip="Bulletin de paie",
    month="juillet 2026",
    heading="BULLETIN DE PAIE",
    period_label="Période",
    period="du 1er au 31 juillet 2026",
    paid_label="Payé le",
    pay_date="31 juillet 2026",
    employee="SALARIÉE",
    role="Ingénieure logiciel confirmée — niveau 3.2",
    staff_label="Matricule",
    joined_label="Entrée le",
    joined_date="4 septembre 2023",
    net_paid="NET À PAYER",
    transferred="Virement sur le compte enregistré",
    hour="h",
    day="j",
    earnings_heading="Éléments de paie",
    quantity="Nombre",
    unit_rate="Taux unitaire",
    earnings_amount="Montant",
    earnings=(
        "Salaire de base mensuel",
        "Heures supplémentaires, 8 premières (125 %)",
        "Astreinte de week-end",
        "Prime d’ancienneté",
    ),
    gross_pay="SALAIRE BRUT",
    employee_share="Part salariale",
    employer_share="Part patronale",
    contribution="Cotisation",
    base="Base",
    rate="Taux",
    amount="Montant",
    lines=(
        "SANTÉ, MATERNITÉ, INVALIDITÉ, DÉCÈS",
        "Assurance maladie et maternité",
        "Complémentaire santé",
        "Indemnités journalières",
        "RETRAITE",
        "Assurance vieillesse plafonnée",
        "Assurance vieillesse déplafonnée",
        "Retraite complémentaire, tranche 1",
        "Retraite complémentaire, tranche 2",
        "Contribution d’équilibre, tranche 1",
        "Contribution d’équilibre, tranche 2",
        "FAMILLE ET CHÔMAGE",
        "Allocations familiales",
        "Assurance chômage",
        "Garantie des salaires",
        "AUTRES COTISATIONS PATRONALES",
        "Accidents du travail",
        "Contribution solidarité autonomie",
        "Taxe d’apprentissage",
        "Formation professionnelle",
        "CSG ET CRDS",
        "CSG déductible",
        "CSG et CRDS non déductibles",
    ),
    total_contributions="TOTAL DES COTISATIONS",
    net_before_tax="NET À PAYER AVANT IMPÔT",
    total_cost="COÛT TOTAL DU MOIS POUR L’EMPLOYEUR",
    summary="Récapitulatif",
    this_month="Ce mois",
    year_to_date="Cumul annuel",
    summary_lines=(
        "Salaire brut",
        "Cotisations salariales",
        "Cotisations patronales",
        "Net imposable",
        "Prélèvement à la source, 11.20 %",
    ),
    net_paid_row="NET À PAYER",
    leave="CONGÉS PAYÉS",
    leave_earned="Acquis cette année",
    leave_taken="pris",
    leave_remaining="solde",
    working_time="Temps de travail : 35 h par semaine",
    mentions=(
        "Bulletin à conserver sans limitation de durée · HQF Development · "
        "42 lot les Genêts, 13480 Calas, France · SIRET 752 492 777 00012 · APE 6202A"
    ),
)

# The payslip in Dutch.
DUTCH = Words(
    lang="nl-NL",
    logo_alt="Het logo van HQF Development",
    payslip="Loonstrook",
    month="Juli 2026",
    heading="LOONSTROOK",
    period_label="Periode",
    period="1 – 31 juli 2026",
    paid_label="Betaald op",
    pay_date="31 juli 2026",
    employee="WERKNEMER",
    role="Senior software-engineer — schaal 3.2",
    staff_label="Personeelsnr.",
    joined_label="In dienst",
    joined_date="4 september 2023",
    net_paid="NETTO BETAALD",
    transferred="Overgemaakt naar de bekende rekening",
    hour="h",
    day="d",
    earnings_heading="Inkomsten",
    quantity="Aantal",
    unit_rate="Tarief",
    earnings_amount="Bedrag",
    earnings=(
        "Maandelijks basissalaris",
        "Overwerk, eerste acht uur (125 %)",
        "Bereikbaarheidsdienst, weekend",
        "Dienstjarentoeslag",
    ),
    gross_pay="BRUTOLOON",
    employee_share="Deel werknemer",
    employer_share="Deel werkgever",
    contribution="Premie",
    base="Grondslag",
    rate="Tarief",
    amount="Bedrag",
    lines=(
        "ZIEKTE, MOEDERSCHAP, INVALIDITEIT, OVERLIJDEN",
        "Ziekte- en moederschapsverzekering",
        "Aanvullende ziektekostendekking",
        "Dagelijkse ziekte-uitkering",
        "PENSIOEN",
        "Staatspensioen, gemaximeerd",
        "Staatspensioen, niet gemaximeerd",
        "Aanvullend pensioen, schijf 1",
        "Aanvullend pensioen, schijf 2",
        "Evenwichtsbijdrage, schijf 1",
        "Evenwichtsbijdrage, schijf 2",
        "GEZIN EN WERKLOOSHEID",
        "Kinderbijslag",
        "Werkloosheidsverzekering",
        "Loongarantiefonds",
        "OVERIGE WERKGEVERSPREMIES",
        "Dekking arbeidsongevallen",
        "Solidariteitsbijdrage autonomie",
        "Leerlingwezenheffing",
        "Heffing permanente scholing",
        "SOCIALE HEFFINGEN",
        "Sociale heffing, aftrekbaar",
        "Sociale en schuldheffing, niet aftrekbaar",
    ),
    total_contributions="TOTAAL PREMIES",
    net_before_tax="NETTO VÓÓR INKOMSTENBELASTING",
    total_cost="TOTALE MAANDKOSTEN VOOR DE WERKGEVER",
    summary="Overzicht",
    this_month="Deze maand",
    year_to_date="Dit jaar tot nu",
    summary_lines=(
        "Brutoloon",
        "Premies werknemer",
        "Premies werkgever",
        "Belastbaar loon",
        "Ingehouden inkomstenbelasting tegen 11,20 %",
    ),
    net_paid_row="NETTO BETAALD",
    leave="BETAALD VERLOF",
    leave_earned="Opgebouwd dit jaar",
    leave_taken="opgenomen",
    leave_remaining="resterend",
    working_time="Arbeidsduur: 35 u per week",
    mentions=(
        "Bewaar deze loonstrook onbeperkt · HQF Development · 42 lot les Genêts, "
        "13480 Calas, Frankrijk · SIRET 752 492 777 00012 · APE 6202A"
    ),
)

# The payslip in Portuguese.
PORTUGUESE = Words(
    lang="pt-PT",
    logo_alt="A marca da HQF Development",
    payslip="Recibo de vencimento",
    month="Julho de 2026",
    heading="RECIBO DE VENCIMENTO",
    period_label="Período",
    period="1 – 31 de julho de 2026",
    paid_label="Pago em",
    pay_date="31 de julho de 2026",
    employee="TRABALHADOR",
    role="Engenheiro de software sénior — nível 3.2",
    staff_label="N.º de funcionário",
    joined_label="Admissão",
    joined_date="4 de setembro de 2023",
    net_paid="LÍQUIDO PAGO",
    transferred="Transferido para a conta registada",
    hour="h",
    day="d",
    earnings_heading="Remunerações",
    quantity="Quantidade",
    unit_rate="Valor unitário",
    earnings_amount="Montante",
    earnings=(
        "Vencimento base mensal",
        "Horas extra, primeiras oito horas (125 %)",
        "Prevenção, fim de semana",
        "Diuturnidades",
    ),
    gross_pay="REMUNERAÇÃO ILÍQUIDA",
    employee_share="Parte do trabalhador",
    employer_share="Parte da entidade patronal",
    contribution="Contribuição",
    base="Base",
    rate="Taxa",
    amount="Montante",
    lines=(
        "DOENÇA, MATERNIDADE, INVALIDEZ, MORTE",
        "Seguro de doença e maternidade",
        "Seguro de saúde complementar",
        "Subsídio diário de doença",
        "REFORMA",
        "Pensão pública, com teto",
        "Pensão pública, sem teto",
        "Pensão complementar, escalão 1",
        "Pensão complementar, escalão 2",
        "Contribuição de equilíbrio, escalão 1",
        "Contribuição de equilíbrio, escalão 2",
        "FAMÍLIA E DESEMPREGO",
        "Abonos de família",
        "Seguro de desemprego",
        "Fundo de garantia salarial",
        "OUTRAS CONTRIBUIÇÕES DA ENTIDADE PATRONAL",
        "Seguro de acidentes de trabalho",
        "Contribuição solidária para a autonomia",
        "Taxa de aprendizagem",
        "Taxa de formação contínua",
        "CONTRIBUIÇÕES SOCIAIS",
        "Contribuição social, dedutível",
        "Contribuição social e para a dívida, não dedutíveis",
    ),
    total_contributions="TOTAL DE CONTRIBUIÇÕES",
    net_before_tax="LÍQUIDO ANTES DO IMPOSTO SOBRE O RENDIMENTO",
    total_cost="CUSTO TOTAL DO MÊS PARA A ENTIDADE PATRONAL",
    summary="Resumo",
    this_month="Este mês",
    year_to_date="Acumulado no ano",
    summary_lines=(
        "Remuneração ilíquida",
        "Contribuições do trabalhador",
        "Contribuições da entidade patronal",
        "Rendimento coletável",
        "Imposto sobre o rendimento retido a 11,20 %",
    ),
    net_paid_row="LÍQUIDO PAGO",
    leave="FÉRIAS PAGAS",
    leave_earned="Adquiridas este ano",
    leave_taken="gozadas",
    leave_remaining="por gozar",
    working_time="Horário de trabalho: 35 h semanais",
    mentions=(
        "Guarde este recibo sem limite de tempo · HQF Development · 42 lot les "
        "Genêts, 13480 Calas, França · SIRET 752 492 777 00012 · APE 6202A"
    ),
)

# The payslip in Italian.
ITALIAN = Words(
    lang="it-IT",
    logo_alt="Il marchio di HQF Development",
    payslip="Busta paga",
    month="Luglio 2026",
    heading="BUSTA PAGA",
    period_label="Periodo",
    period="1 – 31 luglio 2026",
    paid_label="Pagata il",
    pay_date="31 luglio 2026",
    employee="DIPENDENTE",
    role="Ingegnere del software senior — livello 3.2",
    staff_label="Matricola",
    joined_label="Assunto il",
    joined_date="4 settembre 2023",
    net_paid="NETTO PAGATO",
    transferred="Accreditato sul conto registrato",
    hour="h",
    day="g",
    earnings_heading="Competenze",
    quantity="Quantità",
    unit_rate="Tariffa unitaria",
    earnings_amount="Importo",
    earnings=(
        "Stipendio base mensile",
        "Straordinari, prime otto ore (125 %)",
        "Reperibilità, fine settimana",
        "Scatto di anzianità",
    ),
    gross_pay="RETRIBUZIONE LORDA",
    employee_share="Quota dipendente",
    employer_share="Quota datore di lavoro",
    contribution="Contributo",
    base="Imponibile",
    rate="Aliquota",
    amount="Importo",
    lines=(
        "MALATTIA, MATERNITÀ, INVALIDITÀ, MORTE",
        "Assicurazione malattia e maternità",
        "Copertura sanitaria integrativa",
        "Indennità giornaliera di malattia",
        "PENSIONE",
        "Pensione pubblica, con massimale",
        "Pensione pubblica, senza massimale",
        "Pensione integrativa, fascia 1",
        "Pensione integrativa, fascia 2",
        "Contributo di equilibrio, fascia 1",
        "Contributo di equilibrio, fascia 2",
        "FAMIGLIA E DISOCCUPAZIONE",
        "Assegni familiari",
        "Assicurazione contro la disoccupazione",
        "Fondo di garanzia retributiva",
        "ALTRI CONTRIBUTI DEL DATORE DI LAVORO",
        "Assicurazione infortuni sul lavoro",
        "Contributo di solidarietà per l’autonomia",
        "Contributo per l’apprendistato",
        "Contributo per la formazione continua",
        "PRELIEVI SOCIALI",
        "Prelievo sociale, deducibile",
        "Prelievo sociale e contributo al debito, non deducibili",
    ),
    total_contributions="TOTALE CONTRIBUTI",
    net_before_tax="NETTO PRIMA DELL’IMPOSTA SUL REDDITO",
    total_cost="COSTO TOTALE DEL MESE PER IL DATORE DI LAVORO",
    summary="Riepilogo",
    this_month="Questo mese",
    year_to_date="Da inizio anno",
    summary_lines=(
        "Retribuzione lorda",
        "Contributi del dipendente",
        "Contributi del datore di lavoro",
        "Imponibile fiscale",
        "Imposta sul reddito trattenuta all’11,20 %",
    ),
    net_paid_row="NETTO PAGATO",
    leave="FERIE RETRIBUITE",
    leave_earned="Maturate quest’anno",
    leave_taken="godute",
    leave_remaining="residue",
    working_time="Orario di lavoro: 35 h settimanali",
    mentions=(
        "Conservare questa busta paga senza limiti di tempo · HQF Development · 42 "
        "lot les Genêts, 13480 Calas, Francia · SIRET 752 492 777 00012 · APE 6202A"
    ),
)

# The payslip in Spanish.
SPANISH = Words(
    lang="es-ES",
    logo_alt="El logotipo de HQF Development",
    payslip="Nómina",
    month="Julio de 2026",
    heading="NÓMINA",
    period_label="Periodo",
    period="1 – 31 de julio de 2026",
    paid_label="Pagada el",
    pay_date="31 de julio de 2026",
    employee="EMPLEADO",
    role="Ingeniero de software sénior — grado 3.2",
    staff_label="N.º de personal",
    joined_label="Alta",
    joined_date="4 de septiembre de 2023",
    net_paid="LÍQUIDO PAGADO",
    transferred="Transferido a la cuenta registrada",
    hour="h",
    day="d",
    earnings_heading="Devengos",
    quantity="Cantidad",
    unit_rate="Precio unitario",
    earnings_amount="Importe",
    earnings=(
        "Salario base mensual",
        "Horas extra, primeras ocho horas (125 %)",
        "Guardia, fin de semana",
        "Complemento de antigüedad",
    ),
    gross_pay="SALARIO BRUTO",
    employee_share="Parte del empleado",
    employer_share="Parte del empleador",
    contribution="Cotización",
    base="Base",
    rate="Tipo",
    amount="Importe",
    lines=(
        "SALUD, MATERNIDAD, INVALIDEZ, FALLECIMIENTO",
        "Seguro de enfermedad y maternidad",
        "Seguro médico complementario",
        "Subsidio diario por enfermedad",
        "JUBILACIÓN",
        "Pensión pública, con tope",
        "Pensión pública, sin tope",
        "Pensión complementaria, tramo 1",
        "Pensión complementaria, tramo 2",
        "Cotización de equilibrio, tramo 1",
        "Cotización de equilibrio, tramo 2",
        "FAMILIA Y DESEMPLEO",
        "Prestaciones familiares",
        "Seguro de desempleo",
        "Fondo de garantía salarial",
        "OTRAS COTIZACIONES DEL EMPLEADOR",
        "Cobertura de accidentes de trabajo",
        "Contribución solidaria por la autonomía",
        "Tasa de aprendizaje",
        "Tasa de formación continua",
        "RECARGOS SOCIALES",
        "Recargo social, deducible",
        "Recargo social y tasa de deuda, no deducibles",
    ),
    total_contributions="TOTAL COTIZACIONES",
    net_before_tax="LÍQUIDO ANTES DEL IMPUESTO SOBRE LA RENTA",
    total_cost="COSTE TOTAL DEL MES PARA EL EMPLEADOR",
    summary="Resumen",
    this_month="Este mes",
    year_to_date="En el año",
    summary_lines=(
        "Salario bruto",
        "Cotizaciones del empleado",
        "Cotizaciones del empleador",
        "Base imponible",
        "Retención del impuesto sobre la renta al 11,20 %",
    ),
    net_paid_row="LÍQUIDO PAGADO",
    leave="VACACIONES PAGADAS",
    leave_earned="Generadas este año",
    leave_taken="disfrutadas",
    leave_remaining="pendientes",
    working_time="Jornada: 35 h semanales",
    mentions=(
        "Conserve esta nómina sin límite de tiempo · HQF Development · 42 lot les "
        "Genêts, 13480 Calas, Francia · SIRET 752 492 777 00012 · APE 6202A"
    ),
)

# The payslip in German.
GERMAN = Words(
    lang="de-DE",
    logo_alt="Das Logo von HQF Development",
    payslip="Gehaltsabrechnung",
    month="Juli 2026",
    heading="GEHALTSABRECHNUNG",
    period_label="Zeitraum",
    period="1. – 31. Juli 2026",
    paid_label="Gezahlt am",
    pay_date="31. Juli 2026",
    employee="MITARBEITER",
    role="Senior-Softwareentwickler — Stufe 3.2",
    staff_label="Personalnr.",
    joined_label="Eintritt",
    joined_date="4. September 2023",
    net_paid="AUSGEZAHLT",
    transferred="Auf das hinterlegte Konto überwiesen",
    hour="h",
    day="T",
    earnings_heading="Bezüge",
    quantity="Menge",
    unit_rate="Satz",
    earnings_amount="Betrag",
    earnings=(
        "Monatliches Grundgehalt",
        "Überstunden, erste acht Stunden (125 %)",
        "Rufbereitschaft, Wochenende",
        "Betriebszugehörigkeitszulage",
    ),
    gross_pay="BRUTTOBEZÜGE",
    employee_share="Arbeitnehmeranteil",
    employer_share="Arbeitgeberanteil",
    contribution="Beitrag",
    base="Basis",
    rate="Satz",
    amount="Betrag",
    lines=(
        "KRANKHEIT, MUTTERSCHAFT, INVALIDITÄT, TOD",
        "Kranken- und Mutterschaftsversicherung",
        "Krankenzusatzversicherung",
        "Krankentagegeld",
        "RENTE",
        "Gesetzliche Rente, gedeckelt",
        "Gesetzliche Rente, ungedeckelt",
        "Zusatzrente, Stufe 1",
        "Zusatzrente, Stufe 2",
        "Ausgleichsbeitrag, Stufe 1",
        "Ausgleichsbeitrag, Stufe 2",
        "FAMILIE UND ARBEITSLOSIGKEIT",
        "Familienbeihilfen",
        "Arbeitslosenversicherung",
        "Lohngarantiefonds",
        "SONSTIGE ARBEITGEBERBEITRÄGE",
        "Arbeitsunfallversicherung",
        "Solidaritätsbeitrag für die Pflege",
        "Ausbildungsabgabe",
        "Weiterbildungsabgabe",
        "SOZIALABGABEN",
        "Sozialabgabe, abzugsfähig",
        "Sozialabgabe und Schuldentilgungsabgabe, nicht abzugsfähig",
    ),
    total_contributions="BEITRÄGE GESAMT",
    net_before_tax="NETTO VOR EINKOMMENSTEUER",
    total_cost="GESAMTKOSTEN DES MONATS FÜR DEN ARBEITGEBER",
    summary="Übersicht",
    this_month="Dieser Monat",
    year_to_date="Seit Jahresbeginn",
    summary_lines=(
        "Bruttobezüge",
        "Arbeitnehmerbeiträge",
        "Arbeitgeberbeiträge",
        "Steuerpflichtiges Entgelt",
        "Einbehaltene Einkommensteuer zu 11,20 %",
    ),
    net_paid_row="AUSGEZAHLT",
    leave="BEZAHLTER URLAUB",
    leave_earned="In diesem Jahr erworben",
    leave_taken="genommen",
    leave_remaining="verbleibend",
    working_time="Arbeitszeit: 35 Std. pro Woche",
    mentions=(
        "Diese Gehaltsabrechnung unbefristet aufbewahren · HQF Development · 42 lot "
        "les Genêts, 13480 Calas, Frankreich · SIRET 752 492 777 00012 · APE 6202A"
    ),
)


# 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 round2(value: float) -> float:
    """A value rounded to the hundredth, the way every figure on a payslip is carried.

    Each line is rounded before it is added, so the totals are the sum of what is
    printed.
    """
    hundredths = value * 100.0
    return math.floor(hundredths + 0.5) / 100.0


def amount(value: float) -> str:
    """An amount, as a payslip writes it: "4 647.59"."""
    units, hundredths = f"{value:.2f}".split(".")
    grouped = ""
    for index, digit in enumerate(units):
        if index > 0 and (len(units) - index) % 3 == 0:
            grouped += " "
        grouped += digit
    return f"{grouped}.{hundredths}"


def percent(rate: float) -> str:
    """A rate, as a payslip writes it: "6.90 %".

    A rate of nothing is a dash, so that a column of rates reads as a column.
    """
    if rate == 0.0:
        return "—"
    return f"{rate:.2f} %"


class Payroll:
    """What the month comes to: the gross pay, the two sides of the contributions, and
    the surcharge that taxable pay takes back.
    """

    def __init__(self) -> None:
        """Adds the earnings up, then charges every contribution against them."""
        self.gross = sum(
            round2(earning.quantity * earning.unit_rate) for earning in EARNINGS
        )
        self.employee = 0.0
        self.employer = 0.0
        self.non_deductible = 0.0

        for line in LINES:
            if not isinstance(line, Charge):
                continue

            base = self.base(line.base)
            share = round2(base * line.deducted / 100.0)
            self.employee += share
            self.employer += round2(base * line.charged / 100.0)
            if line.non_deductible:
                self.non_deductible += share

    def base(self, base: str) -> float:
        """The figure a contribution's rates are applied to."""
        if base == CAPPED:
            return CEILING
        if base == UPPER_BAND:
            return self.gross - CEILING
        if base == SURCHARGE:
            return round2(self.gross * SURCHARGE_SHARE)
        return self.gross

    def net_before_tax(self) -> float:
        """Gross pay less everything the employee contributes."""
        return round2(self.gross - self.employee)

    def taxable(self) -> float:
        """What income tax is charged on: net pay before tax, plus the share of the
        social surcharges that tax does not let through.
        """
        return round2(self.net_before_tax() + self.non_deductible)

    def tax(self) -> float:
        """The tax the employer withholds and pays over."""
        return round2(self.taxable() * TAX_RATE / 100.0)

    def net_paid(self) -> float:
        """What lands in the employee's account."""
        return round2(self.net_before_tax() - self.tax())


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 rule(content: hqf_pdf.Content, y: float, width: float, color: hqf_pdf.Rgb) -> None:
    """A horizontal rule from ``LEFT`` to ``RIGHT`` at height ``y``, marked as layout: it
    separates what is on the page and says nothing itself.
    """
    content.begin_artifact(hqf_pdf.Artifact.Layout)
    content.set_stroke(color)
    content.set_line_width(width)
    content.move_to(LEFT, y)
    content.line_to(RIGHT, y)
    content.stroke()
    content.end_marked()


def pad() -> hqf_pdf.Padding:
    """The padding every cell of every table on this page is set in."""
    return hqf_pdf.Padding.symmetric(4.0, 1.5)


def figure(font: hqf_pdf.FontHandle, size: float, value: str) -> hqf_pdf.Cell:
    """A cell holding a figure: small, right-aligned, centred in its row."""
    return hqf_pdf.Cell(
        font,
        size,
        value,
        padding=pad(),
        align=hqf_pdf.Align.Right,
        valign=hqf_pdf.VAlign.Middle,
    )


def heading(
    font: hqf_pdf.FontHandle,
    label: str,
    align: hqf_pdf.Align = hqf_pdf.Align.Left,
    span: int = 1,
) -> hqf_pdf.Cell:
    """A heading cell: white on the accent, centred in its row."""
    return hqf_pdf.Cell(
        font,
        7.0,
        label,
        padding=pad(),
        fill=ACCENT,
        color=hqf_pdf.Rgb.gray(1.0),
        align=align,
        span=span,
        valign=hqf_pdf.VAlign.Middle,
    )


def earnings_table(
    font: hqf_pdf.FontHandle, words: Words, payroll: Payroll
) -> hqf_pdf.Table:
    """The earnings table: what the month pays, line by line, and the gross it comes
    to.
    """
    # The description takes whatever the three figure columns leave it.
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(70.0),
            hqf_pdf.ColumnWidth.points(70.0),
            hqf_pdf.ColumnWidth.points(80.0),
        ],
        TABLE_WIDTH,
    )

    table = hqf_pdf.Table(columns)
    table.header(1)
    table.row_headers(1)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8, color=ACCENT))
    table.rule(
        hqf_pdf.Rule.horizontal_other(),
        hqf_pdf.Stroke(0.25, color=hqf_pdf.Rgb.gray(0.82)),
    )
    table.rule(hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.8, color=ACCENT))
    table.rule(hqf_pdf.Rule.horizontal_from_end(1), hqf_pdf.Stroke(0.8, color=ACCENT))

    table.push(
        hqf_pdf.Row(
            cells=[
                heading(font, words.earnings_heading),
                heading(font, words.quantity, hqf_pdf.Align.Right),
                heading(font, words.unit_rate, hqf_pdf.Align.Right),
                heading(font, words.earnings_amount, hqf_pdf.Align.Right),
            ],
            min_height=15.0,
        )
    )

    for index, (earning, label) in enumerate(zip(EARNINGS, words.earnings)):
        unit = words.unit(earning.unit)
        if unit:
            quantity = f"{earning.quantity:.2f} {unit}"
        else:
            quantity = f"{earning.quantity:.2f}"

        table.push(
            hqf_pdf.Row(
                cells=[
                    hqf_pdf.Cell(
                        font,
                        7.5,
                        label,
                        padding=pad(),
                        valign=hqf_pdf.VAlign.Middle,
                    ),
                    figure(font, 7.5, quantity),
                    figure(font, 7.5, f"{earning.unit_rate:.4f}"),
                    figure(
                        font, 7.5, amount(round2(earning.quantity * earning.unit_rate))
                    ),
                ],
                min_height=13.0,
                fill=hqf_pdf.Rgb.gray(0.96) if index % 2 else None,
            )
        )

    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(
                    font,
                    8.0,
                    words.gross_pay,
                    span=3,
                    align=hqf_pdf.Align.Right,
                    padding=pad(),
                    valign=hqf_pdf.VAlign.Middle,
                ),
                figure(font, 8.0, amount(payroll.gross)),
            ],
            min_height=15.0,
        )
    )

    return table


def contributions_table(
    font: hqf_pdf.FontHandle, words: Words, payroll: Payroll
) -> hqf_pdf.Table:
    """The contributions table: two tiers of headings, a heading row for each family of
    contributions, one row per contribution, and the three totals.
    """
    # Four figure columns for the two shares, one for the base, and whatever is left
    # over for the wording.
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(62.0),
            hqf_pdf.ColumnWidth.points(42.0),
            hqf_pdf.ColumnWidth.points(62.0),
            hqf_pdf.ColumnWidth.points(42.0),
            hqf_pdf.ColumnWidth.points(62.0),
        ],
        TABLE_WIDTH,
    )

    table = hqf_pdf.Table(columns)
    # Both tiers of the heading repeat if the table ever continues on a second page.
    table.header(2)
    table.row_headers(1)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8, color=ACCENT))
    table.rule(
        hqf_pdf.Rule.horizontal_other(),
        hqf_pdf.Stroke(0.25, color=hqf_pdf.Rgb.gray(0.85)),
    )
    table.rule(
        hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.4, color=hqf_pdf.Rgb.gray(1.0))
    )
    table.rule(hqf_pdf.Rule.horizontal(2), hqf_pdf.Stroke(0.8, color=ACCENT))
    table.rule(hqf_pdf.Rule.horizontal_from_end(3), hqf_pdf.Stroke(0.8, color=ACCENT))
    table.rule(
        hqf_pdf.Rule.vertical(2), hqf_pdf.Stroke(0.4, color=hqf_pdf.Rgb.gray(0.72))
    )
    table.rule(
        hqf_pdf.Rule.vertical(4), hqf_pdf.Stroke(0.4, color=hqf_pdf.Rgb.gray(0.72))
    )

    table.push(
        hqf_pdf.Row(
            cells=[
                heading(font, "", span=2),
                heading(font, words.employee_share, hqf_pdf.Align.Center, span=2),
                heading(font, words.employer_share, hqf_pdf.Align.Center, span=2),
            ],
            min_height=13.0,
        )
    )
    table.push(
        hqf_pdf.Row(
            cells=[
                heading(font, words.contribution),
                heading(font, words.base, hqf_pdf.Align.Right),
                heading(font, words.rate, hqf_pdf.Align.Right),
                heading(font, words.amount, hqf_pdf.Align.Right),
                heading(font, words.rate, hqf_pdf.Align.Right),
                heading(font, words.amount, hqf_pdf.Align.Right),
            ],
            min_height=13.0,
        )
    )

    for line, label in zip(LINES, words.lines):
        if isinstance(line, Section):
            table.push(
                hqf_pdf.Row(
                    cells=[
                        hqf_pdf.Cell(
                            font,
                            7.0,
                            label,
                            span=6,
                            padding=pad(),
                            color=ACCENT,
                            valign=hqf_pdf.VAlign.Middle,
                        )
                    ],
                    fill=hqf_pdf.Rgb.gray(0.91),
                    min_height=12.0,
                )
            )
            continue

        base = payroll.base(line.base)

        def share(rate: float, base: float = base) -> str:
            return "" if rate == 0.0 else amount(round2(base * rate / 100.0))

        table.push(
            hqf_pdf.Row(
                cells=[
                    hqf_pdf.Cell(
                        font,
                        7.0,
                        label,
                        padding=pad(),
                        valign=hqf_pdf.VAlign.Middle,
                    ),
                    figure(font, 7.0, amount(base)),
                    figure(font, 7.0, percent(line.deducted)),
                    figure(font, 7.0, share(line.deducted)),
                    figure(font, 7.0, percent(line.charged)),
                    figure(font, 7.0, share(line.charged)),
                ],
                min_height=11.5,
            )
        )

    contribution_totals(table, font, words, payroll)

    return table


def contribution_totals(
    table: hqf_pdf.Table, font: hqf_pdf.FontHandle, words: Words, payroll: Payroll
) -> None:
    """Closes the contributions table off: the two columns of shares added up under
    their own heads, then the net pay and the cost of the month.
    """
    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(
                    font,
                    8.0,
                    words.total_contributions,
                    span=3,
                    align=hqf_pdf.Align.Right,
                    padding=pad(),
                    valign=hqf_pdf.VAlign.Middle,
                ),
                figure(font, 8.0, amount(payroll.employee)),
                hqf_pdf.Cell(font, 8.0, "", padding=pad()),
                figure(font, 8.0, amount(payroll.employer)),
            ],
            min_height=15.0,
        )
    )

    # The last two lines are boxed off the grid so that they read as totals rather than
    # as more lines of it: the label carries the box's left edge and the figure its
    # right, so the two trace one box between them.
    stroke = hqf_pdf.Stroke(0.8, color=ACCENT)
    box_margin = hqf_pdf.Margin.symmetric(0.0, 2.0)
    label_border = hqf_pdf.Border(top=stroke, bottom=stroke, left=stroke)
    value_border = hqf_pdf.Border(top=stroke, bottom=stroke, right=stroke)

    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(
                    font,
                    8.0,
                    words.net_before_tax,
                    span=3,
                    align=hqf_pdf.Align.Right,
                    padding=pad(),
                    margin=box_margin,
                    border=label_border,
                    valign=hqf_pdf.VAlign.Middle,
                ),
                hqf_pdf.Cell(
                    font,
                    8.0,
                    amount(payroll.net_before_tax()),
                    align=hqf_pdf.Align.Right,
                    padding=pad(),
                    margin=box_margin,
                    border=value_border,
                    valign=hqf_pdf.VAlign.Middle,
                ),
                hqf_pdf.Cell(font, 8.0, "", span=2, padding=pad()),
            ],
            min_height=15.0,
        )
    )

    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(
                    font,
                    7.5,
                    words.total_cost,
                    span=5,
                    align=hqf_pdf.Align.Right,
                    padding=pad(),
                    margin=box_margin,
                    border=label_border,
                    valign=hqf_pdf.VAlign.Middle,
                ),
                hqf_pdf.Cell(
                    font,
                    7.5,
                    amount(round2(payroll.gross + payroll.employer)),
                    align=hqf_pdf.Align.Right,
                    padding=pad(),
                    margin=box_margin,
                    border=value_border,
                    valign=hqf_pdf.VAlign.Middle,
                ),
            ],
            min_height=14.0,
        )
    )


def cumulative_table(
    font: hqf_pdf.FontHandle, words: Words, payroll: Payroll
) -> hqf_pdf.Table:
    """The cumulative table: what the month came to beside what the year has come to,
    the income tax withheld, and the net that is paid over.
    """
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(96.0),
            hqf_pdf.ColumnWidth.points(96.0),
        ],
        TABLE_WIDTH,
    )

    table = hqf_pdf.Table(columns)
    table.header(1)
    table.row_headers(1)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.8, color=ACCENT))
    table.rule(
        hqf_pdf.Rule.horizontal_other(),
        hqf_pdf.Stroke(0.25, color=hqf_pdf.Rgb.gray(0.82)),
    )
    table.rule(hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.8, color=ACCENT))
    table.rule(hqf_pdf.Rule.horizontal_from_end(1), hqf_pdf.Stroke(0.8, color=ACCENT))

    table.push(
        hqf_pdf.Row(
            cells=[
                heading(font, words.summary),
                heading(font, words.this_month, hqf_pdf.Align.Right),
                heading(font, words.year_to_date, hqf_pdf.Align.Right),
            ],
            min_height=15.0,
        )
    )

    values = [
        payroll.gross,
        payroll.employee,
        payroll.employer,
        payroll.taxable(),
        payroll.tax(),
    ]

    for index, (label, value) in enumerate(zip(words.summary_lines, values)):
        table.push(
            hqf_pdf.Row(
                cells=[
                    hqf_pdf.Cell(
                        font, 7.5, label, padding=pad(), valign=hqf_pdf.VAlign.Middle
                    ),
                    figure(font, 7.5, amount(value)),
                    figure(font, 7.5, amount(round2(value * MONTHS))),
                ],
                min_height=13.0,
                fill=hqf_pdf.Rgb.gray(0.96) if index % 2 else None,
            )
        )

    net_paid = payroll.net_paid()
    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(
                    font,
                    8.5,
                    words.net_paid_row,
                    padding=pad(),
                    color=ACCENT,
                    valign=hqf_pdf.VAlign.Middle,
                ),
                hqf_pdf.Cell(
                    font,
                    8.5,
                    amount(net_paid),
                    padding=pad(),
                    align=hqf_pdf.Align.Right,
                    valign=hqf_pdf.VAlign.Middle,
                    color=ACCENT,
                ),
                figure(font, 8.5, amount(round2(net_paid * MONTHS))),
            ],
            min_height=17.0,
        )
    )

    return table


def begin(
    content: hqf_pdf.Content, marks: hqf_pdf.Marks, tag: str, alt: str | None = None
) -> hqf_pdf.StructElement:
    """Opens a run marked under ``tag``, numbered from the page's counter, and hands
    back the element the tree points at it with. ``Content.end_marked`` closes the run.
    """
    number = marks.next_id()
    content.begin_tagged(tag, number)
    return hqf_pdf.StructElement(tag, children=[(0, number)], alt=alt)


def letterhead(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    logo: hqf_pdf.ImageHandle,
    words: Words,
    marks: hqf_pdf.Marks,
) -> list[hqf_pdf.StructElement]:
    """Draws the letterhead: the mark, the employer, the word the page is, and the
    month it covers, closed off by a rule. Hands back the elements standing for what it
    drew, in the order they are read: the title and the month first.
    """
    logo_w, logo_h = logo.fit_within(62.25, 62.25)
    mark = begin(content, marks, "Figure", words.logo_alt)
    content.draw_image(logo, LEFT, 826.5 - logo_h, logo_w, logo_h)
    content.end_marked()

    address = begin(content, marks, "P")
    for y, line in (
        (782.0, "42 lot les Genêts, 13480 Calas, France"),
        (771.0, "SIRET 752 492 777 00012 · APE 6202A · contact@hqf-pdf.com"),
    ):
        text(content, font, 8.5, LEFT, y, MUTED, line)
    content.end_marked()

    title = begin(content, marks, "H1")
    text_right(content, font, 26.0, RIGHT, 802.0, ACCENT, words.heading)
    content.end_marked()

    period = begin(content, marks, "P")
    text_right(
        content, font, 9.0, RIGHT, 783.0, INK, f"{words.period_label} {words.period}"
    )
    text_right(
        content, font, 9.0, RIGHT, 771.0, MUTED, f"{words.paid_label} {words.pay_date}"
    )
    content.end_marked()

    rule(content, 758.0, 1.2, ACCENT)
    return [title, period, mark, address]


def employee(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    words: Words,
    payroll: Payroll,
    marks: hqf_pdf.Marks,
) -> list[hqf_pdf.StructElement]:
    """Draws who is being paid and — set apart on the right — what they are paid.
    Hands back the elements standing for what it drew: a heading and a paragraph for
    each side.
    """
    who = begin(content, marks, "H2")
    text(content, font, 7.5, LEFT, 742.0, MUTED, words.employee)
    content.end_marked()

    named = begin(content, marks, "P")
    text(content, font, 11.0, LEFT, 728.0, INK, EMPLOYEE_NAME)
    text(content, font, 8.0, LEFT, 715.0, MUTED, words.role)
    text(
        content,
        font,
        8.0,
        LEFT,
        704.0,
        MUTED,
        f"{words.staff_label} {EMPLOYEE_ID} · {words.joined_label} {words.joined_date}",
    )
    content.end_marked()

    paid = begin(content, marks, "H2")
    text_right(content, font, 7.5, RIGHT, 742.0, MUTED, words.net_paid)
    content.end_marked()

    figure_run = begin(content, marks, "P")
    text_right(
        content, font, 18.0, RIGHT, 724.0, ACCENT, f"{amount(payroll.net_paid())} EUR"
    )
    text_right(content, font, 8.0, RIGHT, 708.0, MUTED, words.transferred)
    content.end_marked()

    return [who, named, paid, figure_run]


def footer(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    words: Words,
    top: float,
    marks: hqf_pdf.Marks,
) -> list[hqf_pdf.StructElement]:
    """Draws the leave the employee stands at, and the small print the foot of the page
    carries. Hands back the elements standing for what it drew.
    """
    leave = begin(content, marks, "H2")
    text(content, font, 7.5, LEFT, top, ACCENT, words.leave)
    content.end_marked()

    day = words.day
    counted = (
        f"{words.leave_earned} {LEAVE_EARNED:.2f} {day} · "
        f"{words.leave_taken} {LEAVE_TAKEN:.2f} {day} · "
        f"{words.leave_remaining} {LEAVE_EARNED - LEAVE_TAKEN:.2f} {day}"
    )
    counts = begin(content, marks, "P")
    text(content, font, 8.0, LEFT, top - 13.0, INK, counted)
    content.end_marked()

    hours = begin(content, marks, "P")
    text_right(content, font, 8.0, RIGHT, top - 13.0, MUTED, words.working_time)
    content.end_marked()

    rule(content, 74.0, 0.5, hqf_pdf.Rgb.gray(0.8))
    mentions = begin(content, marks, "P")
    text(
        content,
        font,
        6.5,
        LEFT + (TABLE_WIDTH - font.measure(words.mentions, 6.5)) / 2.0,
        62.0,
        MUTED,
        words.mentions,
    )
    content.end_marked()

    return [leave, counts, hours, mentions]


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

    title = f"{words.payslip} — {words.month}"
    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    # The accessibility claim, which is what a buyer's validator is pointed at: it is
    # judged against the tree, the artifacts, the embedded font and the title all at
    # once.
    document.set_ua_conformance(hqf_pdf.PdfUa.One)
    document.set_info("Title", title)
    document.set_metadata(
        hqf_pdf.Metadata(title=title, producer="hqf-pdf", created=DRAWN_UP)
    )

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

    payroll = Payroll()

    content = hqf_pdf.Content()
    marks = hqf_pdf.Marks()
    children = letterhead(content, font, logo, words, marks)
    children += employee(content, font, words, payroll, marks)

    # The three tables are stacked down the page, each one starting a fixed gap below
    # where the one above it stopped. Each names its headings under a name of its own,
    # so no two tables share one.
    top = 686.0
    for name, table in (
        ("earnings", earnings_table(font, words, payroll)),
        ("contributions", contributions_table(font, words, payroll)),
        ("summary", cumulative_table(font, words, payroll)),
    ):
        placed = table.fit(LEFT, top, top - 80.0, 0)
        described = hqf_pdf.TaggedTable(name)
        described.add(placed, content, 0, marks)
        children.append(described.finish())
        top -= placed.height + 18.0

    children += footer(content, font, words, top - 4.0, marks)

    page = hqf_pdf.Page(PAGE_WIDTH, PAGE_HEIGHT)
    page.set_content(content)
    document.add_page(page)
    document.set_structure(
        hqf_pdf.StructureTree(
            lang=words.lang,
            children=[hqf_pdf.StructElement("Document", children=children)],
        )
    )

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, {amount(payroll.gross)} gross, "
        f"{amount(payroll.net_paid())} net"
    )


if __name__ == "__main__":
    main()
