"""Tests para render_markdown_table."""

import sys
import os

sys.path.insert(0, os.path.dirname(__file__))
from render_markdown_table import render_markdown_table


def test_caso_normal():
    rows = [
        {"nombre": "Alice", "edad": 30},
        {"nombre": "Bob", "edad": 25},
    ]
    result = render_markdown_table(rows)
    lines = result.split("\n")
    assert lines[0] == "| nombre | edad |"
    assert lines[1] == "|---|---|"
    assert lines[2] == "| Alice | 30 |"
    assert lines[3] == "| Bob | 25 |"
    assert len(lines) == 4


def test_rows_vacio():
    assert render_markdown_table([]) == ""


def test_rows_vacio_con_columns():
    result = render_markdown_table([], columns=["a", "b"])
    assert result == "| a | b |\n|---|---|"


def test_columns_explicitas_ordenan():
    rows = [{"b": 2, "a": 1}]
    result = render_markdown_table(rows, columns=["a", "b"])
    lines = result.split("\n")
    assert lines[0] == "| a | b |"
    assert lines[2] == "| 1 | 2 |"


def test_escape_de_pipes():
    rows = [{"col": "x|y|z"}]
    result = render_markdown_table(rows)
    assert "x\\|y\\|z" in result


def test_none_bool_y_saltos_de_linea():
    rows = [{"a": None, "b": True, "c": False, "d": "line1\nline2"}]
    result = render_markdown_table(rows)
    data_line = result.split("\n")[2]
    assert data_line == "|  | true | false | line1<br>line2 |"


def test_max_rows_truncado():
    rows = [{"n": i} for i in range(5)]
    result = render_markdown_table(rows, max_rows=2)
    lines = result.split("\n")
    # header + separator + 2 data rows + truncation note
    assert len(lines) == 5
    assert lines[-1] == "_... 2 de 5 filas_"


def test_max_rows_sin_truncar():
    rows = [{"n": 1}, {"n": 2}]
    result = render_markdown_table(rows, max_rows=5)
    assert "filas_" not in result
    assert len(result.split("\n")) == 4


if __name__ == "__main__":
    test_caso_normal()
    test_rows_vacio()
    test_rows_vacio_con_columns()
    test_columns_explicitas_ordenan()
    test_escape_de_pipes()
    test_none_bool_y_saltos_de_linea()
    test_max_rows_truncado()
    test_max_rows_sin_truncar()
    print("All tests passed.")
