Source code for bragi_quantum.gui.rendering.archive_rendering

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   QC2 @ CHALMERS CALIBRATION TOOLKIT
#   (c) 2026 Chalmers University of Technology and Project Contributors
# ──────────────────────────────────────────────────────────────────────────
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       https://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
# ──────────────────────────────────────────────────────────────────────────
#   CONTRIBUTORS list:
#
#   Axel Andersson, axean@chalmers.se
#   Yanchen Lin, linya@chalmers.se
#   Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


"""
Standalone HTML renderer for the archive sidebar view.

The archive view is a two-pane layout: a fixed sidebar listing timestamped
run folders (newest first) and an iframe that loads the selected run's
index.html. The sidebar polls /runs on an interval (see POLL_INTERVAL_SECONDS)
so new runs appear live without a page reload.

The markup lives in sibling files so the HTML/CSS/JS is editable as such:
  - ``archive.html``            full page; ``<!-- RUN_ITEMS -->`` marks where
                                the server-rendered date groups are injected,
                                and ``@@ARCHIVE_JS@@`` marks where
                                ``archive-logic.js`` (the sidebar's client
                                logic — linted/type-checked as a real .js
                                file) is embedded.
  - ``archive_date_group.html`` one date's collapsible group; ``{date}``/
                                ``{count}``/``{collapsed_class}`` are filled
                                in, and ``<!-- DATE_GROUP_ITEMS -->`` marks
                                where that date's run rows are injected.
  - ``archive_run_item.html``   one run row; ``{name}``/``{src}``/``{date}``/
                                ``{time}``/``{title}``/``{sessions}``/
                                ``{qubits}``/``{meta_html}`` are filled from a
                                run descriptor (``{meta_html}`` is the
                                pluralized "N sessions"/"N qubits" column).

This module is pure rendering — it does no filesystem I/O. Callers pass run
descriptors (the same dicts the ``/runs`` endpoint returns), so the initial
server render and the live poll can never describe a folder differently.

Runs are grouped into one collapsible section per calendar day (``date``).
Callers must pass ``runs`` newest-first (the ``/runs`` contract already
guarantees this), so same-day runs are contiguous and a single pass of
``itertools.groupby`` is enough to bucket them. Only the most recent day
starts expanded; every other day starts collapsed. The sidebar JS then
layers the user's own per-date toggles (persisted in ``localStorage``) on
top of that default when the page loads.

Usage::

    from bragi_quantum.gui.rendering.archive_rendering import build_archive_html
    html = build_archive_html(run_descriptors)
"""

from itertools import groupby

from bragi_quantum.gui.rendering.templates import load as _load_template

_RUN_ITEMS_MARKER = "<!-- RUN_ITEMS -->"
_DATE_GROUP_ITEMS_MARKER = "<!-- DATE_GROUP_ITEMS -->"
_POLL_INTERVAL_MARKER = "__POLL_INTERVAL_MS__"
_ARCHIVE_JS_MARKER = "@@ARCHIVE_JS@@"

# Shown as a run's title when its orchestrator had no ``name`` (so the run
# folder carries no sanitized suffix). Mirrors the JS fallback in archive.html.
UNTITLED_RUN = "Untitled run"

# Single source of truth for the sidebar's /runs poll cadence. The value is
# injected into archive.html's setInterval() and is also what the server logs
# at startup, so the two can never drift apart.
POLL_INTERVAL_SECONDS = 5


def _run_title(run: dict) -> str:
    return run["sanitized_run_name"] or UNTITLED_RUN


def _count_label(display: str, singular: str) -> str:
    """Pluralize a sidebar count ("1 session", "3 sessions"); pass the "—"
    live-run placeholder through unchanged."""
    try:
        count = int(display)
    except ValueError:
        return f"{display} {singular}s"
    return f"{count} {singular}{'' if count == 1 else 's'}"


def _meta_html(run: dict) -> str:
    """Build the run row's sessions/qubits column, mirroring the JS
    ``metaHTML`` the live poll uses, so the pre-poll render matches it.

    A crashed/errored run already carries its own status icon and row tint
    (set by the live poll's ``renderStatus``) — this column just states the
    counts, it doesn't need to also announce failure.
    """
    sessions = _count_label(run["sessions_display"], "session")
    qubits = _count_label(run["qubits_display"], "qubit")
    return f"<div>{sessions}</div><div>{qubits}</div>"


def _render_run_item(item_template: str, run: dict) -> str:
    return item_template.format(
        name=run["name"],
        src=run["src"],
        date=run["date"],
        time=run["time"],
        title=_run_title(run),
        sessions=run["sessions_display"],
        qubits=run["qubits_display"],
        meta_html=_meta_html(run),
    )


def _render_date_groups(runs: list[dict]) -> str:
    item_template = _load_template("archive_run_item.html").strip()
    group_template = _load_template("archive_date_group.html").strip()
    groups_html = []
    for index, (date, day_runs) in enumerate(
        groupby(runs, key=lambda run: run["date"])
    ):
        day_runs = list(day_runs)
        items_html = "".join(_render_run_item(item_template, run) for run in day_runs)
        # Newest-first input means index 0 is always the most recent day.
        collapsed_class = "" if index == 0 else " collapsed"
        group_html = group_template.format(
            date=date, count=len(day_runs), collapsed_class=collapsed_class
        )
        groups_html.append(group_html.replace(_DATE_GROUP_ITEMS_MARKER, items_html))
    return "".join(groups_html)


[docs] def build_archive_html(runs: list[dict]) -> str: """Build the archive sidebar page from pre-computed run descriptors. Each ``run`` is one of the dicts ``/runs`` returns. Required keys: ``name``, ``src``, ``date``, ``time``, ``sanitized_run_name``, ``sessions_display``, ``qubits_display``. The display values are pre-gated by the descriptor (``—`` while a run is live, final counts once done). The ``.run-status`` slot is left empty here — the poll JS fills it (spinner / done / error) so status lives in one place, not duplicated in Python. ``runs`` must be newest-first, same as the ``/runs`` contract. """ items_html = _render_date_groups(runs) page = _load_template("archive.html") page = page.replace(_RUN_ITEMS_MARKER, items_html) page = page.replace(_ARCHIVE_JS_MARKER, _load_template("archive-logic.js")) page = page.replace(_POLL_INTERVAL_MARKER, str(POLL_INTERVAL_SECONDS * 1000)) return page