#
#   Imandra Inc.
#
#   speclogician/presentation/renderers/scenario.py
#

from __future__ import annotations

from rich import box
from rich.panel import Panel
from rich.table import Table
from rich.text import Text

from speclogician.presentation.ctx import RenderCtx
from speclogician.presentation.models.scenario import ScenarioPM


def _status_style(kind: str) -> str:
    k = (kind or "").lower()
    if k == "valid":
        return "green"
    if k == "missing":
        return "yellow"
    if k == "inconsistent":
        return "red"
    return "dim"


def _section(label: str) -> Text:
    return Text(label, style="italic magenta")


def _bool_badge(v: bool) -> Text:
    return Text("✓" if v else "✗", style=("green" if v else "red"))


def _names_block(items: list[str], *, empty: str = "—") -> Text:
    """
    Render a list of names as plain styled text (no Syntax, no black background).
    """
    if not items:
        return Text(empty, style="dim")

    out = Text()
    for i, name in enumerate(items):
        if i:
            out.append("\n")
        out.append("• ", style="dim")
        out.append(name, style="cyan")
    return out


def render_scenario(pm: ScenarioPM, *, ctx: RenderCtx) -> Panel:
    status_style = _status_style(pm.status.kind)

    title = Text.assemble(
        ("Scenario: ", "bold"),
        (pm.name or "(unnamed)", "cyan"),
    )

    b = box.MINIMAL if ctx.compact else box.SIMPLE
    t = Table(
        show_header=False,
        box=b,
        pad_edge=False,
        show_edge=False,
        expand=False,
    )
    t.add_column(style="italic dim", no_wrap=True)
    t.add_column(no_wrap=False)

    # optional id
    if ctx.show_ids:
        t.add_row("comp_id", Text(pm.comp_id, style="dim"))

    # Predicates
    t.add_row(_section("Predicates"), Text(""))
    t.add_row("  given", _names_block(pm.given))
    t.add_row("  when", _names_block(pm.when))
    t.add_row("  then", _names_block(pm.then))

    # Checks
    t.add_row(_section("Checks"), Text(""))
    t.add_row("  given consistent", _bool_badge(pm.given_preds_consistent))
    t.add_row("  when consistent", _bool_badge(pm.when_preds_consistent))
    t.add_row("  all consistent", _bool_badge(pm.all_preds_consistent))

    # Missing components
    if getattr(ctx, "show_missing_components", False) and pm.status.kind == "missing":
        t.add_row(_section("Missing"), Text(""))
        t.add_row("  predicates", _names_block(pm.status.missing_preds))
        t.add_row("  transitions", _names_block(pm.status.missing_trans))

    return Panel(t, title=title, border_style=status_style)