#
#   Imandra Inc.
#
#   speclogician/presentation/renderers/container.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 rich.rule import Rule

from speclogician.presentation.ctx import RenderCtx
from speclogician.presentation.models.container import ArtifactContainerPM
from speclogician.presentation.renderers.trace import render_test_trace, render_log_trace
from speclogician.presentation.renderers.data_artifact import render_doc_ref, render_src_code_ref


def _group_with_separators(renderables: list[object], *, style: str = "dim") -> Group:
    """
    Render list items with a horizontal separator between them.
    """
    parts: list[object] = []
    for i, r in enumerate(renderables):
        parts.append(r)
        if i < len(renderables) - 1:
            parts.append(Rule(style=style))
    return Group(*parts)


def render_artifact_container(pm: ArtifactContainerPM, *, ctx: RenderCtx):
    b = box.MINIMAL if ctx.compact else box.SIMPLE

    # --- Counts table ---
    t = Table(
        show_header=False,
        box=b,
        show_edge=False,
        pad_edge=False,
        expand=False,          
    )

    t.add_column(no_wrap=True)
    t.add_column(
        justify="right",
        width=6,
    )

    def section(title: str) -> None:
        t.add_row(
            Text(title, style="bold magenta"),
            Text(""),
        )

    def metric(label: str, value: int, *, icon: str = "•") -> None:
        t.add_row(
            Text(f"  {icon} {label}", style="dim"),
            Text(str(value)),
        )

    c = pm.counts

    section("Test traces")
    metric("Total", c.num_test_traces_total)
    metric("Matched", c.num_test_traces_matched, icon="✓")
    metric("Valid IML", c.num_test_traces_logic_good, icon="✓")

    section("Log traces")
    metric("Total", c.num_log_traces_total)
    metric("Matched", c.num_log_traces_matched, icon="✓")
    metric("Valid IML", c.num_log_traces_logic_good, icon="✓")

    section("Source code refs")
    metric("Total", c.num_src_code_arts_total)
    metric("Matched", c.num_src_code_arts_matched, icon="✓")

    section("Doc refs")
    metric("Total", c.num_doc_arts_total)
    metric("Matched", c.num_doc_arts_matched, icon="✓")

    if ctx.show_stats_only:
        return Panel(
            t,
            title="[bold]Artifacts[/bold]",
            border_style="magenta",
        )

    blocks: list[object] = [Panel(t, title="[bold]Counts[/bold]", border_style="magenta")]

    # --- Split by type ---
    items = pm.items

    if items.test_traces:
        rendered = [render_test_trace(x, ctx=ctx) for x in items.test_traces]
        blocks.append(
            Panel(
                _group_with_separators(rendered),
                title=f"[bold]Test traces[/bold] ({len(items.test_traces)})",
                border_style="cyan",
            )
        )

    if items.log_traces:
        rendered = [render_log_trace(x, ctx=ctx) for x in items.log_traces]
        blocks.append(
            Panel(
                _group_with_separators(rendered),
                title=f"[bold]Log traces[/bold] ({len(items.log_traces)})",
                border_style="cyan",
            )
        )

    if items.doc_refs:
        rendered = [render_doc_ref(x, ctx=ctx) for x in items.doc_refs]
        blocks.append(
            Panel(
                _group_with_separators(rendered),
                title=f"[bold]Doc refs[/bold] ({len(items.doc_refs)})",
                border_style="green",
            )
        )

    if items.src_code_refs:
        rendered = [render_src_code_ref(x, ctx=ctx) for x in items.src_code_refs]
        blocks.append(
            Panel(
                _group_with_separators(rendered),
                title=f"[bold]Src code refs[/bold] ({len(items.src_code_refs)})",
                border_style="green",
            )
        )

    return Panel(Group(*blocks), title="[bold]Artifact container[/bold]", border_style="magenta")