"""The device a document's colours are meant for, stated in the file.

The Python twin of the `write_output_intent` example in Rust. A page that fills
a rectangle with four numbers has said four numbers and nothing about what
colour they are. The output intent is the answer: the profile of the device the
job was prepared for, travelling inside the file, together with the name of that
device's condition. An archival claim makes stating one compulsory, and a job
separated for a press states the press's own profile rather than the screen the
library falls back to.

The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which
set the page is written in. What the file states is not language: the name of the
condition and the name of the profile travel as they are given.

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

from __future__ import annotations

import sys
from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The left edge of everything.
LEFT = 70.0

# How far in from LEFT the values of the intent's rows are set, which is the room the
# labels beside them have.
VALUE_IN = 100.0

# The date the document says it was made on, so that two runs of the example produce the
# same bytes.
MADE = "2026-07-25T10:00:00+02:00"

# The claim the file makes, which is a name the standard gives rather than anything a
# language says.
CLAIM = "PDF/A-3B"

# The tints the ramp runs through, all the profile's channels together.
TINTS = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
# The width of one cell of the ramp, the gap to the next, and its height.
RAMP_CELL = 38.0
RAMP_GAP = 3.5
RAMP_HEIGHT = 86.0
# The bottom edge of the ramp.
RAMP_Y = 440.0

# The size of one channel swatch, the gap to the next, and their bottom edge.
CHANNEL_CELL = 90.0
CHANNEL_GAP = 15.0
CHANNEL_Y = 230.0

# What the caller says the condition is called when a profile is handed over on the
# command line. ISO 32000-1 table 365 asks for `Custom` where the condition is not one
# of the registered characterizations, which a profile read off a disk is not.
CUSTOM = "Custom"
# What the condition is called when the library's own profile is used, and the name that
# profile is registered under.
BUILT_IN = ("sRGB", "sRGB IEC61966-2.1")


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

    # The title over the page, which is also the title the file states.
    title: str
    # The two lines under the title.
    intro: tuple[str, str]
    # The heading over the panel that lists what the file carries.
    intent_panel: str
    # The heading over the ramp, and the line under it.
    profile_panel: str
    profile_note: str
    # The heading over the channel swatches.
    channel_panel: str
    # What the five rows of the intent panel are called.
    rows: tuple[str, str, str, str, str]
    # What stands between the size of the profile and what it describes, so that the row
    # reads as one sentence in every language.
    profile_size: str
    # What follows the name of the claim on its row.
    claim_note: str
    # What a colour is made of, in words, in a grey, an RGB and a CMYK space.
    described: tuple[str, str, str]
    # The device a profile describes, one entry per kind of device a profile names in
    # its header, then what is said of bytes that name none.
    classes: tuple[str, str, str, str, str, str, str, str]
    # The one channel of a grey space.
    gray_channels: tuple[str]
    # The three channels of an RGB space.
    rgb_channels: tuple[str, str, str]
    # The four channels of a CMYK space.
    cmyk_channels: tuple[str, str, str, str]
    # What the caller is told a profile of their own would do, under the swatches.
    closing: tuple[str, str]
    # What the condition is called when a profile is handed over on the command line,
    # which is prose rather than a registered name.
    custom_info: str

    def channels(self, space) -> tuple[str, ...]:
        """The channels a colour in `space` is made of, in the order their numbers
        are given."""
        return {
            hqf_pdf.DeviceSpace.Gray: self.gray_channels,
            hqf_pdf.DeviceSpace.Rgb: self.rgb_channels,
            hqf_pdf.DeviceSpace.Cmyk: self.cmyk_channels,
        }[space]

    def describes(self, space) -> str:
        """What a colour in `space` is made of, in words."""
        return {
            hqf_pdf.DeviceSpace.Gray: self.described[0],
            hqf_pdf.DeviceSpace.Rgb: self.described[1],
            hqf_pdf.DeviceSpace.Cmyk: self.described[2],
        }[space]

    def device(self, profile: bytes) -> str:
        """The device the profile `profile` describes, in words."""
        found = hqf_pdf.icc_profile_class(profile)
        kinds = (
            hqf_pdf.DeviceClass.Input,
            hqf_pdf.DeviceClass.Display,
            hqf_pdf.DeviceClass.Output,
            hqf_pdf.DeviceClass.DeviceLink,
            hqf_pdf.DeviceClass.ColorSpace,
            hqf_pdf.DeviceClass.Abstract,
            hqf_pdf.DeviceClass.NamedColor,
        )
        for kind, said in zip(kinds, self.classes):
            if found == kind:
                return said
        return self.classes[7]


# The page in English.
ENGLISH = Words(
    title="What the numbers on this page mean",
    intro=(
        "A file states the device it was prepared for, and the profile of that "
        "device travels inside it.",
        "Nothing else in the file says what its colours are: the numbers alone "
        "say none.",
    ),
    intent_panel="The output intent this file carries",
    profile_panel="The same profile, painted through",
    profile_note=(
        "One profile does both jobs: it says what the file is for, and it is "
        "what these swatches are painted in. The file carries it once."
    ),
    channel_panel="One channel at a time, at full strength",
    rows=("Condition", "Description", "Profile", "Device", "Claim"),
    profile_size=" bytes, describing ",
    claim_note=", which makes stating one compulsory",
    described=("grey", "red, green and blue", "the four printing inks"),
    classes=(
        "a scanner or a camera, which reads colour in",
        "a screen",
        "a press or a printer",
        "a link from one device to another",
        "a space colours are converted through",
        "an effect applied along the way",
        "a book of named colours",
        "nothing a profile names",
    ),
    gray_channels=("Grey",),
    rgb_channels=("Red", "Green", "Blue"),
    cmyk_channels=("Cyan", "Magenta", "Yellow", "Black"),
    closing=(
        "Hand a press profile on the command line and the page is drawn in its "
        "inks instead, under its own",
        "condition. A file that paints in CMYK and states a screen is a file a "
        "validator refuses.",
    ),
    custom_info="A profile handed over on the command line",
)

# The page in French.
FRENCH = Words(
    title="Ce que veulent dire les nombres de cette page",
    intro=(
        ("Un fichier indique l’appareil pour lequel il a été préparé, et il contient "
         "le profil de cet appareil."),
        ("Rien d’autre dans le fichier ne dit ce que sont ses couleurs : les nombres "
         "seuls n’en disent rien."),
    ),
    intent_panel="L’intention de sortie que déclare ce fichier",
    profile_panel="Le même profil, utilisé pour peindre",
    profile_note=(
        (("Un seul profil fait les deux : il dit à quoi sert le fichier, et c’est lui "
          "qui peint ces pastilles. Le fichier ne le contient qu’une fois."))
    ),
    channel_panel="Une composante à la fois, à pleine intensité",
    rows=("Condition", "Description", "Profil", "Appareil", "Déclaration"),
    profile_size=" octets, décrivant ",
    claim_note=", qui oblige à en déclarer une",
    described=(
        "le gris",
        "le rouge, le vert et le bleu",
        "les quatre encres d’imprimerie",
    ),
    classes=(
        "un scanner ou un appareil photo, qui lit la couleur",
        "un écran",
        "une presse ou une imprimante",
        "un lien d’un appareil à un autre",
        "un espace par lequel passent les conversions",
        "un effet appliqué en chemin",
        "un nuancier de couleurs nommées",
        "rien qu’un profil nomme",
    ),
    gray_channels=("Gris",),
    rgb_channels=("Rouge", "Vert", "Bleu"),
    cmyk_channels=("Cyan", "Magenta", "Jaune", "Noir"),
    closing=(
        ("Passez un profil de presse en ligne de commande et la page est peinte avec "
         "ses encres, selon sa propre"),
        ("condition d’impression. Un fichier qui peint en CMJN en annonçant un écran "
         "est refusé par un validateur."),
    ),
    custom_info="Un profil passé en ligne de commande",
)

# The page in Dutch.
DUTCH = Words(
    title="Wat de getallen op deze pagina betekenen",
    intro=(
        "Een bestand zegt voor welk apparaat het is voorbereid, en het profiel van "
        "dat apparaat reist erin mee.",
        "Niets anders in het bestand zegt wat zijn kleuren zijn: de getallen alleen "
        "zeggen niets.",
    ),
    intent_panel="De uitvoerintentie die dit bestand bevat",
    profile_panel="Hetzelfde profiel, gebruikt om te schilderen",
    profile_note=(
        "Eén profiel doet beide: het zegt waarvoor het bestand is, en deze stalen "
        "zijn ermee ingekleurd. Het bestand bevat het één keer."
    ),
    channel_panel="Eén kanaal tegelijk, op volle sterkte",
    rows=("Conditie", "Omschrijving", "Profiel", "Apparaat", "Claim"),
    profile_size=" bytes, dat beschrijft:",
    claim_note=", wat het noemen ervan verplicht maakt",
    described=("grijs", "rood, groen en blauw", "de vier drukinkten"),
    classes=(
        "een scanner of camera, die kleur leest in",
        "een scherm",
        "een pers of printer",
        "een koppeling van het ene apparaat naar het andere",
        "een ruimte waarlangs kleuren worden omgezet",
        "een effect onderweg toegepast",
        "een boek met benoemde kleuren",
        "niets wat een profiel noemt",
    ),
    gray_channels=("Grijs",),
    rgb_channels=("Rood", "Groen", "Blauw"),
    cmyk_channels=("Cyaan", "Magenta", "Geel", "Zwart"),
    closing=(
        "Geef op de opdrachtregel een persprofiel mee en de pagina wordt in zijn "
        "inkten getekend, onder zijn eigen",
        "conditie. Een bestand dat in CMYK schildert en een scherm opgeeft, is een "
        "bestand dat een validator weigert.",
    ),
    custom_info="Een profiel meegegeven op de opdrachtregel",
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="O que significam os números desta página",
    intro=(
        "Um ficheiro indica o dispositivo para que foi preparado, e o perfil desse "
        "dispositivo viaja dentro dele.",
        "Nada mais no ficheiro diz quais são as suas cores: os números sozinhos não "
        "dizem nenhuma.",
    ),
    intent_panel="A intenção de saída que este ficheiro leva",
    profile_panel="O mesmo perfil, usado para pintar",
    profile_note=(
        "Um perfil faz os dois trabalhos: diz para que serve o ficheiro, e é nele que "
        "estas amostras são pintadas. O ficheiro leva-o uma vez."
    ),
    channel_panel="Um canal de cada vez, a plena intensidade",
    rows=("Condição", "Descrição", "Perfil", "Dispositivo", "Declaração"),
    profile_size=" bytes, que descrevem",
    claim_note=", o que torna obrigatório indicar um",
    described=("cinzento", "vermelho, verde e azul", "as quatro tintas de impressão"),
    classes=(
        "um digitalizador ou uma câmara, que lê a cor em",
        "um ecrã",
        "uma máquina de impressão ou uma impressora",
        "uma ligação de um dispositivo a outro",
        "um espaço através do qual se convertem cores",
        "um efeito aplicado pelo caminho",
        "um catálogo de cores com nome",
        "nada que um perfil nomeie",
    ),
    gray_channels=("Cinzento",),
    rgb_channels=("Vermelho", "Verde", "Azul"),
    cmyk_channels=("Ciano", "Magenta", "Amarelo", "Preto"),
    closing=(
        "Passe um perfil de impressão na linha de comandos e a página é desenhada nas "
        "suas tintas, sob a sua",
        "condição. Um ficheiro que pinta em CMYK e declara um ecrã é um ficheiro que "
        "um validador recusa.",
    ),
    custom_info="Um perfil passado na linha de comandos",
)

# The page in Italian.
ITALIAN = Words(
    title="Cosa significano i numeri di questa pagina",
    intro=(
        "Un file indica il dispositivo per cui è stato preparato, e il profilo di "
        "quel dispositivo viaggia al suo interno.",
        "Nient’altro nel file dice quali sono i suoi colori: i numeri da soli non ne "
        "dicono nessuno.",
    ),
    intent_panel="L’intento di uscita che porta questo file",
    profile_panel="Lo stesso profilo, usato per dipingere",
    profile_note=(
        "Un profilo fa entrambi i lavori: dice a cosa serve il file, ed è con esso "
        "che sono dipinti questi campioni. Il file lo porta una volta."
    ),
    channel_panel="Un canale alla volta, a piena intensità",
    rows=("Condizione", "Descrizione", "Profilo", "Dispositivo", "Dichiarazione"),
    profile_size=" byte, che descrivono",
    claim_note=", il che rende obbligatorio indicarne uno",
    described=("grigio", "rosso, verde e blu", "i quattro inchiostri da stampa"),
    classes=(
        "uno scanner o una fotocamera, che legge il colore in",
        "uno schermo",
        "una macchina da stampa o una stampante",
        "un collegamento da un dispositivo a un altro",
        "uno spazio attraverso cui si convertono i colori",
        "un effetto applicato lungo il percorso",
        "una mazzetta di colori con nome",
        "nulla che un profilo nomini",
    ),
    gray_channels=("Grigio",),
    rgb_channels=("Rosso", "Verde", "Blu"),
    cmyk_channels=("Ciano", "Magenta", "Giallo", "Nero"),
    closing=(
        "Passate un profilo da stampa sulla riga di comando e la pagina è disegnata "
        "nei suoi inchiostri, sotto la sua",
        "condizione. Un file che dipinge in CMYK e dichiara uno schermo è un file che "
        "un validatore rifiuta.",
    ),
    custom_info="Un profilo passato sulla riga di comando",
)

# The page in Spanish.
SPANISH = Words(
    title="Lo que significan los números de esta página",
    intro=(
        "Un archivo indica el dispositivo para el que se preparó, y el perfil de ese "
        "dispositivo viaja dentro de él.",
        "Nada más en el archivo dice cuáles son sus colores: los números solos no "
        "dicen ninguno.",
    ),
    intent_panel="La intención de salida que lleva este archivo",
    profile_panel="El mismo perfil, usado para pintar",
    profile_note=(
        "Un perfil hace los dos trabajos: dice para qué es el archivo, y con él se "
        "pintan estas muestras. El archivo lo lleva una vez."
    ),
    channel_panel="Un canal cada vez, a plena intensidad",
    rows=("Condición", "Descripción", "Perfil", "Dispositivo", "Declaración"),
    profile_size=" bytes, que describen ",
    claim_note=", lo que obliga a indicar uno",
    described=("gris", "rojo, verde y azul", "las cuatro tintas de imprenta"),
    classes=(
        "un escáner o una cámara, que lee el color en",
        "una pantalla",
        "una prensa o una impresora",
        "un enlace de un dispositivo a otro",
        "un espacio por el que se convierten los colores",
        "un efecto aplicado por el camino",
        "un muestrario de colores con nombre",
        "nada que nombre un perfil",
    ),
    gray_channels=("Gris",),
    rgb_channels=("Rojo", "Verde", "Azul"),
    cmyk_channels=("Cian", "Magenta", "Amarillo", "Negro"),
    closing=(
        "Pase un perfil de imprenta en la línea de órdenes y la página se dibuja en "
        "sus tintas, bajo su propia",
        "condición. Un archivo que pinta en CMYK y declara una pantalla es un archivo "
        "que un validador rechaza.",
    ),
    custom_info="Un perfil pasado en la línea de órdenes",
)

# The page in German.
GERMAN = Words(
    title="Was die Zahlen auf dieser Seite bedeuten",
    intro=(
        "Eine Datei nennt das Gerät, für das sie gemacht ist, und dessen Profil reist "
        "mit.",
        "Nichts sonst in der Datei sagt, was ihre Farben sind: Die Zahlen allein "
        "sagen es nicht.",
    ),
    intent_panel="Die Ausgabebedingung, die diese Datei trägt",
    profile_panel="Dasselbe Profil, zum Malen verwendet",
    profile_note=(
        "Ein Profil für beide Aufgaben: Es sagt, wofür die Datei ist, und diese "
        "Felder sind darin gemalt. Die Datei trägt es einmal."
    ),
    channel_panel="Ein Kanal nach dem anderen, in voller Stärke",
    rows=("Bedingung", "Beschreibung", "Profil", "Gerät", "Anspruch"),
    profile_size=" Bytes, beschreibt ",
    claim_note=", was die Angabe einer solchen Bedingung zur Pflicht macht",
    described=("Grau", "Rot, Grün und Blau", "die vier Druckfarben"),
    classes=(
        "einen Scanner oder eine Kamera, die Farbe einliest",
        "einen Bildschirm",
        "eine Druckmaschine oder einen Drucker",
        "eine Verbindung von einem Gerät zu einem anderen",
        "einen Farbraum, über den Farben umgerechnet werden",
        "einen unterwegs angewandten Effekt",
        "ein Buch benannter Farben",
        "nichts, was ein Profil benennt",
    ),
    gray_channels=("Grau",),
    rgb_channels=("Rot", "Grün", "Blau"),
    cmyk_channels=("Cyan", "Magenta", "Gelb", "Schwarz"),
    closing=(
        "Mit einem Druckprofil auf der Befehlszeile wird die Seite in dessen Farben "
        "gezeichnet,",
        "unter seiner Bedingung. Eine CMYK-Datei, die einen Bildschirm nennt, lehnt "
        "ein Validator ab.",
    ),
    custom_info="Ein auf der Befehlszeile übergebenes Profil",
)

# 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 heading(content, font, words):
    """Draw the title and the two lines saying what the page is showing."""
    content.draw_text(font, 15.0, LEFT, 780.0, words.title)
    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.35))
    content.draw_text(font, 10.0, LEFT, 762.0, words.intro[0])
    content.draw_text(font, 10.0, LEFT, 748.0, words.intro[1])
    content.restore_state()


def panel_heading(content, font, y, title, under):
    """Draw one panel's heading, with the line under it that a panel may have."""
    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.2))
    content.draw_text(font, 11.0, LEFT, y, title)
    if under is not None:
        content.set_fill(hqf_pdf.Color.gray(0.45))
        content.draw_text(font, 8.0, LEFT, y - 16.0, under)
    content.restore_state()


def intent_panel(content, font, words, intent, profile):
    """Draw the intent's parts, one to a line, as the file carries them."""
    described = words.describes(intent.profile.space)
    values = (
        intent.identifier,
        intent.info,
        f"{len(profile)}{words.profile_size}{described}",
        words.device(profile),
        f"{CLAIM}{words.claim_note}",
    )

    y = 672.0
    for label, value in zip(words.rows, values):
        content.save_state()
        content.set_fill(hqf_pdf.Color.gray(0.45))
        content.draw_text(font, 9.0, LEFT, y, label)
        content.set_fill(hqf_pdf.Color.gray(0.15))
        content.draw_text(font, 9.0, LEFT + VALUE_IN, y, value)
        content.restore_state()
        y -= 18.0


def frame(content, x, y, width, height):
    """Frame a swatch, so that one painted white is a swatch rather than a hole."""
    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.75))
    content.rect(x - 1.0, y - 1.0, width + 2.0, height + 2.0)
    content.fill()
    content.restore_state()


def ramp(content, font, space, width):
    """Draw every channel of the profile at the same tint, none of it to all."""
    x = LEFT
    for tint in TINTS:
        frame(content, x, RAMP_Y, RAMP_CELL, RAMP_HEIGHT)
        content.save_state()
        content.set_fill_space(space)
        content.set_fill_components([tint] * width)
        content.rect(x, RAMP_Y, RAMP_CELL, RAMP_HEIGHT)
        content.fill()
        content.restore_state()

        content.save_state()
        content.set_fill(hqf_pdf.Color.gray(0.45))
        content.draw_text(font, 7.0, x, RAMP_Y - 12.0, f"{tint * 100.0:.0f}%")
        content.restore_state()
        x += RAMP_CELL + RAMP_GAP


def channel_swatches(content, font, space, names):
    """Draw one swatch per channel, each at full strength with the others empty."""
    x = LEFT
    for channel, name in enumerate(names):
        components = [0.0] * len(names)
        components[channel] = 1.0

        frame(content, x, CHANNEL_Y, CHANNEL_CELL, CHANNEL_CELL)
        content.save_state()
        content.set_fill_space(space)
        content.set_fill_components(components)
        content.rect(x, CHANNEL_Y, CHANNEL_CELL, CHANNEL_CELL)
        content.fill()
        content.restore_state()

        content.save_state()
        content.set_fill(hqf_pdf.Color.gray(0.45))
        content.draw_text(font, 8.0, x, CHANNEL_Y - 12.0, name)
        content.restore_state()
        x += CHANNEL_CELL + CHANNEL_GAP


def closing(content, font, words):
    """Draw the closing note under the swatches."""
    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.35))
    content.draw_text(font, 9.0, LEFT, 160.0, words.closing[0])
    content.draw_text(font, 9.0, LEFT, 146.0, words.closing[1])
    content.restore_state()


def stated_for(words):
    """The profile the document is stated for, and what its condition is called.

    The file named on the command line, or the one the library builds.
    """
    if len(sys.argv) > 3:
        return Path(sys.argv[3]).read_bytes(), (CUSTOM, words.custom_info)
    return hqf_pdf.srgb_icc_profile(), BUILT_IN


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("intent.pdf", language)).stem)
    profile, (identifier, info) = stated_for(words)

    described = hqf_pdf.icc_profile_space(profile)
    if described is None:
        raise SystemExit("the profile must describe a grey, RGB or CMYK space")
    intent = hqf_pdf.OutputIntent(
        hqf_pdf.IccBased(profile, described), identifier, info
    )
    names = words.channels(described)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_conformance(hqf_pdf.PdfA.A3B)
    document.set_metadata(
        hqf_pdf.Metadata(
            title=words.title,
            producer="hqf-pdf",
            created=MADE,
        )
    )
    document.set_output_intent(intent)

    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
    space = document.add_color_space(hqf_pdf.IccBased(profile, described))

    content = hqf_pdf.Content()
    heading(content, font, words)
    panel_heading(content, font, 700.0, words.intent_panel, None)
    intent_panel(content, font, words, intent, profile)

    panel_heading(
        content, font, 566.0, words.profile_panel, words.profile_note
    )
    ramp(content, font, space, len(names))

    panel_heading(content, font, 360.0, words.channel_panel, None)
    channel_swatches(content, font, space, names)
    closing(content, font, words)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, stated for {identifier} through a "
        f"profile of {len(profile)} bytes"
    )


if __name__ == "__main__":
    main()
