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

from __future__ import annotations

from speclogician.modeling.domain import DomainModel
from speclogician.presentation.ctx import RenderCtx
from speclogician.presentation.models.domain import (
    DomainModelPM,
    DomainCountsPM,
    DomainCodePM,
)


def build_domain_model_pm(dm: DomainModel, ctx: RenderCtx) -> DomainModelPM:
    counts = DomainCountsPM(
        base_status=dm.base_status,
        base_has_state=dm.base_has_state,
        base_has_action=dm.base_has_action,
        num_state_preds_total=dm.num_state_preds_total,
        num_state_preds_valid_logic=dm.num_state_preds_valid_logic,
        num_state_preds_matched=dm.num_state_preds_matched,
        num_action_preds_total=dm.num_action_preds_total,
        num_action_preds_valid_logic=dm.num_action_preds_valid_logic,
        num_action_preds_matched=dm.num_action_preds_matched,
        num_preds_total=dm.num_preds_total,
        num_preds_valid_logic=dm.num_preds_valid_logic,
        num_preds_matched=dm.num_preds_matched,
        num_trans_total=dm.num_trans_total,
        num_trans_valid_logic=dm.num_trans_valid_logic,
        num_trans_matched=dm.num_trans_matched,
    )

    # Always construct code PM for stable JSON; keep fields empty unless requested.
    code = DomainCodePM()

    if not ctx.show_stats_only and ctx.show_code and not ctx.compact:
        # Base
        if getattr(ctx, "show_base", True):
            code.base = dm.base or ""

        # Predicates
        if getattr(ctx, "show_predicates", True):
            code.state_preds_iml = "\n\n".join(p.to_iml() for p in dm.state_preds).strip()
            code.action_preds_iml = "\n\n".join(p.to_iml() for p in dm.action_preds).strip()

        # Transitions
        if getattr(ctx, "show_transitions", True):
            code.transitions_iml = "\n\n".join(t.to_iml() for t in dm.transitions).strip()

    return DomainModelPM(counts=counts, code=code)