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

from __future__ import annotations

from speclogician.presentation.ctx import RenderCtx
from speclogician.presentation.models.trace import (
    TraceIMLValidityPM,
    TraceCorePM,
    TestTracePM,
    LogTracePM,
)

from speclogician.data.traces import TestTrace, LogTrace


def _build_validity_pm(v) -> TraceIMLValidityPM:
    # v: TraceIMLValidity(iml_valid=IMLValidity, err=...)
    iml_valid = getattr(v, "iml_valid", None)
    # enum -> "valid"/"invalid"/"unknown"
    iml_valid_s = getattr(iml_valid, "value", None) or str(iml_valid)
    return TraceIMLValidityPM(iml_valid=str(iml_valid_s), err=getattr(v, "err", None))


def _build_core_pm(tr: TestTrace | LogTrace) -> TraceCorePM:
    return TraceCorePM(
        art_id=tr.art_id,
        given=tr.given,
        when=tr.when,
        then=tr.then,
        time=tr.time or "",
        iml_validity=_build_validity_pm(tr.iml_validity),
    )


def build_test_trace_pm(tr: TestTrace, ctx: RenderCtx) -> TestTracePM:
    # heavy fields obey ctx.show_code (or rename to ctx.show_contents if you prefer)
    contents = tr.contents if getattr(ctx, "show_code", True) else None
    return TestTracePM(
        core=_build_core_pm(tr),
        name=tr.name,
        filepath=tr.filepath or "",
        language=tr.language,
        contents=contents,
    )


def build_log_trace_pm(tr: LogTrace, ctx: RenderCtx) -> LogTracePM:
    # heavy log contents also obey ctx.show_code
    contents = tr.contents if getattr(ctx, "show_code", True) else None
    return LogTracePM(
        core=_build_core_pm(tr),
        filename=tr.filename,
        contents=contents,
    )
