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

from __future__ import annotations

from speclogician.presentation.ctx import RenderCtx
from speclogician.presentation.models.state_instance import StateInstancePM
from speclogician.presentation.builders.state_instance_summary import (
    build_state_instance_summary_pm,
)

from speclogician.presentation.builders.spec import build_spec_pm
from speclogician.presentation.builders.container import build_artifact_container_pm
from speclogician.presentation.builders.state_diff import build_state_diff_pm
from speclogician.presentation.builders.recommendations import build_recommendations_pm

# NEW: trace reachability builder
from speclogician.presentation.builders.trace_reachability import build_trace_reachability_pm

from speclogician.state.inst import StateInstance


def build_state_instance_pm(si: StateInstance, ctx: RenderCtx) -> StateInstancePM:
    summary_pm = build_state_instance_summary_pm(si, ctx)
    recommendations_pm = build_recommendations_pm(si.recommendations, ctx)

    pm = StateInstancePM(
        summary=summary_pm,
        recommendations=recommendations_pm,
    )

    # Always include analyses unless explicitly suppressed or in compact mode.
    if not ctx.compact:
        pm.trace_reachability = build_trace_reachability_pm(
            getattr(si, "trace_reachability", None),
            si.art_container,
            ctx,
        )

    # -----------------
    # Heavy parts (optional)
    # -----------------
    if not ctx.show_stats_only:
        pm.spec = build_spec_pm(si.spec, ctx)

        if not ctx.compact:
            pm.artifacts = build_artifact_container_pm(si.art_container, ctx)

        pm.state_diff = build_state_diff_pm(si.state_diff, ctx) if si.state_diff is not None else None

    return pm