#
#   Imandra Inc.
#
#   speclogician/presentation/builders/instances_list.py
#

from __future__ import annotations

from speclogician.presentation.ctx import RenderCtx
from speclogician.presentation.models.instances_list import InstancesListPM, InstancesListRowPM
from speclogician.presentation.builders.state_instance_summary import build_state_instance_summary_pm
from speclogician.state.inst import StateInstance


def _changes_str(si: StateInstance) -> str:
    if not (si.changes or []):
        return "-"

    parts: list[str] = []
    for ch in si.changes:
        short = getattr(ch, "short_str", None)
        parts.append(short() if callable(short) else ch.__class__.__name__)
    return ", ".join(parts)


def build_instances_list_pm(states: list[StateInstance], ctx: RenderCtx) -> InstancesListPM:
    rows: list[InstancesListRowPM] = []
    for idx, si in enumerate(states):
        state_label = "latest" if idx == 0 else str(idx)
        rows.append(
            InstancesListRowPM(
                state_label=state_label,
                changes=_changes_str(si),
                summary=build_state_instance_summary_pm(si, ctx=ctx),
            )
        )

    return InstancesListPM(rows=rows)