#!/usr/bin/env python3
"""The cyclic-cluster schematic figure (#247), from public vibe-sketcher APIs only.

A double-column (178 mm) figure in four labelled panels:

(a) the graphene lattice with a 3 x 3 cyclic cluster outlined in a 5 x 5 repeat;
(b) the Wigner-Seitz supercell of that cluster with the boundary atoms filled by
    their weights 1/m;
(c) the cluster's torus beside its unrolled sheet;
(d) the interaction classes as a taxonomy diagram (``interaction-classes.toml``).

Run ``python cyclic_cluster_schematic.py schematic.pdf`` (or ``.svg``/``.png``).
PDF and PNG need the publication extra; the PDF embeds its font. The same
release always writes the same bytes.
"""

from __future__ import annotations

import sys
from pathlib import Path

from vibesketcher.document import crystal, new_document
from vibesketcher.document.solid_build import CellRecipe, build
from vibesketcher.render.cyclic_topology import TopologyOptions, topology_svg
from vibesketcher.render.diagram import diagram_svg, load_spec
from vibesketcher.render.panels import Panel, PanelOptions, cell_width_pt, compose_panels
from vibesketcher.render.periodic import FigureOptions, periodic_figure_svg

HERE = Path(__file__).resolve().parent
CLUSTER = (3, 3, 1)


def panels() -> tuple[list[Panel], PanelOptions]:
    """The four panels and the layout of the figure."""
    layout = PanelOptions(columns=2, column="double", max_height_mm=70)
    width = cell_width_pt(layout)
    graphene = crystal.prototype("graphene", identifier="graphene")
    lattice = periodic_figure_svg(
        graphene, FigureOptions(repeat=(5, 5, 1), cluster=CLUSTER, width=width / 0.75)
    )
    matrix = [[CLUSTER[0], 0, 0], [0, CLUSTER[1], 0], [0, 0, CLUSTER[2]]]
    document = new_document().model_copy(update={"periodic_structures": [graphene]})
    built = build(
        document,
        CellRecipe(
            identifier="ws", source="graphene", choice="wigner_seitz_supercell", matrix=matrix
        ),
    )
    supercell = next(s for s in built.periodic_structures if s.id == "ws")
    ws = periodic_figure_svg(supercell, FigureOptions(ws_supercell=True, width=width / 0.75))
    torus = topology_svg(
        graphene, CLUSTER, TopologyOptions(width=width, caption=False, cell_labels=False)
    )
    spec = load_spec((HERE / "interaction-classes.toml").read_text(encoding="utf-8"), "toml")
    classes = diagram_svg(spec)
    n_c = CLUSTER[0] * CLUSTER[1]
    return [
        Panel(
            svg=lattice.decode(), caption=f"graphene, ${CLUSTER[0]} \\times {CLUSTER[1]}$ cluster"
        ),
        Panel(svg=ws.decode(), caption="Wigner–Seitz supercell, weights $1/m$"),
        Panel(svg=torus.decode(), caption=f"$N_c = {n_c}$ torus and its unrolled sheet"),
        Panel(svg=classes.decode(), caption="interaction classes"),
    ], layout


def figure(fmt: str = "pdf") -> bytes:
    """The composed figure as SVG, PDF or PNG."""
    items, layout = panels()
    return compose_panels(items, layout, fmt)


def main(argv: list[str]) -> int:
    if len(argv) != 2:
        print(__doc__)
        return 2
    output = Path(argv[1])
    output.write_bytes(figure(output.suffix.lstrip(".").lower()))
    print(output)
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
