"""Engagement-data cell — shape pins for the client-facts cell.

The cell (tagged ``engagement-data``) carries client-specific session facts
and lives in the notebook, never in ``.py``. The MASTER ships placeholders;
an engagement copy ships real values — both must stay green, so these pins
check SHAPE only and never assert emptiness (or any particular value).
"""

import json
import pathlib

from discoverylib import build_session, session_json

NOTEBOOK = (
    pathlib.Path(__file__).resolve().parent.parent / "notebooks" / "cx_discovery.ipynb"
)


def test_keys_and_types(engagement):
    assert set(engagement) == {"client", "workshop_date", "facilitator", "attendees"}
    for key in ("client", "workshop_date", "facilitator"):
        assert isinstance(engagement[key], str)
    assert all(isinstance(a, str) for a in engagement["attendees"])


def test_flows_into_export_meta(topics, engagement):
    payload = session_json(build_session(topics, {}), meta=engagement)
    assert payload["meta"]["client"] == engagement["client"]
    assert payload["assessment"] == "CX_Discovery_Workshop"
    json.dumps(payload)          # the attendees tuple serializes as a JSON list


def test_cell_sits_above_the_widgets():
    # Position rule: engagement data must never re-run on a sidebar change,
    # so its cell precedes the widget-defining cell (Mercury re-runs only
    # cells BELOW a changed widget's cell).
    import nbformat

    nb = nbformat.read(NOTEBOOK, as_version=4)
    eng = next(i for i, c in enumerate(nb.cells)
               if "engagement-data" in c.metadata.get("tags", []))
    widgets = next(i for i, c in enumerate(nb.cells)
                   if c.cell_type == "code" and "mr.Select(" in c.source)
    assert eng < widgets, "engagement-data cell must sit above the widget cell"
