"""Box-drawing (``table`` format) renderers for the output framework.

Unicode box-drawing renderers for the ``table`` materialisation strategy.
P2-5 fix (Luis review): upgraded from ASCII ``+-|`` to Unicode
box-drawing characters ``╭─╮│╰╯`` with rounded corners, matching
the specification (§26821).
Extracted from ``_renderers.py`` for file-length compliance (R2-C2 fix).
"""

from __future__ import annotations

from cleveragents.cli.output._renderers import (
    _sanitize,
    _sort_table_rows,
    compute_column_widths,
)
from cleveragents.cli.output.handles import (
    ElementSnapshot,
    Table,
)

# ---------------------------------------------------------------------------
# Box-drawing characters
# ---------------------------------------------------------------------------

_TOP_LEFT = "╭"
_TOP_RIGHT = "╮"
_BOTTOM_LEFT = "╰"
_BOTTOM_RIGHT = "╯"
_HORIZONTAL = "─"
_VERTICAL = "│"
_T_DOWN = "┬"
_T_UP = "┴"
_T_RIGHT = "├"
_T_LEFT = "┤"
_CROSS = "┼"


def _render_table_boxdraw(table: Table) -> str:
    """Render a table using ASCII box-drawing (tabulate style).

    R2-C2 fix: summary row is truncated to ``pad_width`` to prevent
    the row from exceeding the table border width.
    """
    if not table.columns:
        return "(empty table)"

    col_names = [_sanitize(c.name) for c in table.columns]
    rows = _sort_table_rows(table)
    str_rows: list[list[str]] = []
    for row in rows:
        str_rows.append([_sanitize(str(row.get(c.name, ""))) for c in table.columns])

    widths = compute_column_widths(col_names, str_rows)

    def make_border(left: str, mid: str, right: str) -> str:
        return left + mid.join(_HORIZONTAL * (w + 2) for w in widths) + right

    def make_row(cells: list[str]) -> str:
        padded = [f" {c.ljust(w)} " for c, w in zip(cells, widths, strict=False)]
        return _VERTICAL + _VERTICAL.join(padded) + _VERTICAL

    lines: list[str] = []
    if table.title:
        lines.append(_sanitize(table.title))
    lines.append(make_border(_TOP_LEFT, _T_DOWN, _TOP_RIGHT))
    lines.append(make_row(col_names))
    lines.append(make_border(_T_RIGHT, _CROSS, _T_LEFT))
    for row in str_rows:
        lines.append(make_row(row))
    if table.summary:
        lines.append(make_border(_T_RIGHT, _CROSS, _T_LEFT))
        summary_str = "  ".join(
            f"{_sanitize(str(k))}: {_sanitize(str(v))}"
            for k, v in table.summary.items()
        )
        inner_width = sum(w + 2 for w in widths) + (len(widths) - 1)
        pad_width = inner_width - 1
        # Truncate summary to fit within the table border (R2-C2 fix #11).
        if len(summary_str) > pad_width:
            summary_str = summary_str[:pad_width]
        lines.append(f"{_VERTICAL} {summary_str.ljust(pad_width)}{_VERTICAL}")
    lines.append(make_border(_BOTTOM_LEFT, _T_UP, _BOTTOM_RIGHT))

    return "\n".join(lines)


def render_element_table(element: ElementSnapshot) -> str:
    """Dispatch for the ``table`` format (box-drawing for tables,
    colour for colour-capable elements, colour fallback, plain fallback).

    R2-C2 fix #12: colour-capable elements (Tree, Code, Diff) use the
    colour renderer; remaining elements also try colour before plain.
    """
    # Lazy import to avoid circular dependency through __init__.py.
    from cleveragents.cli.output._color_renderers import render_element_color

    if isinstance(element, Table):
        return _render_table_boxdraw(element)
    return render_element_color(element)
