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


from __future__ import annotations

from rich import box
from rich.console import Group
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.recommendations import RecommendationsPM, RecommendationPM


def _kind_style(kind: str) -> str:
    k = (kind or "").lower()
    if k == "error":
        return "red"
    if k == "warning":
        return "yellow"
    if k == "info":
        return "cyan"
    return "green"  # next


def _header(pm: RecommendationsPM) -> Text:
    parts = []
    if pm.num_error:
        parts.append(Text(f"{pm.num_error} error", style="red"))
    if pm.num_warning:
        parts.append(Text(f"{pm.num_warning} warning", style="yellow"))
    if pm.num_next:
        parts.append(Text(f"{pm.num_next} next", style="green"))
    if pm.num_info:
        parts.append(Text(f"{pm.num_info} info", style="cyan"))

    if not parts:
        return Text("No recommendations", style="dim")

    out = Text(" • ").join(parts)
    return out


def _render_item(r: RecommendationPM, *, show_priority: bool) -> list[Text]:
    style = _kind_style(r.kind)
    left = Text(r.kind.upper(), style=f"bold {style}")
    if show_priority:
        left.append(f"  p{r.priority}", style="dim")
    body = Text(r.text)
    return [left, body]


def render_recommendations(pm: RecommendationsPM, *, ctx: RenderCtx) -> Panel:
    b = box.MINIMAL if ctx.compact else box.SIMPLE

    if pm.count == 0:
        body = Text("— none —", style="dim")
        return Panel(body, title="Recommendations", border_style="dim", box=b)

    show_priority = ctx.show_ids  # cheap reuse: if ids are shown, show pri too

    t = Table(
        box=b,
        pad_edge=False,
        show_edge=False,
        expand=True,
        show_header=False,
    )
    t.add_column(style="dim", no_wrap=True)
    t.add_column(no_wrap=False)

    # In compact mode, show fewer items (but keep deterministic)
    items = pm.items
    if ctx.compact and len(items) > 8:
        items = items[:8]

    for r in items:
        left, body = _render_item(r, show_priority=show_priority)
        t.add_row(left, body)

    blocks = [t]
    # show a small header line if useful
    blocks.insert(0, _header(pm))

    return Panel(Group(*blocks), title="Recommendations", border_style="cyan", box=b)