"""Tests para render_table_page_pdfpages."""
from __future__ import annotations

import tempfile
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import pytest


def test_50_filas_con_max_rows_28_genera_2_paginas_en_pdf_no_vacio():
    """50 filas con max_rows=28 genera 2 paginas en pdf no vacio"""
    import sys
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
    from infra.render_table_page_pdfpages import render_table_page_pdfpages
    from matplotlib.backends.backend_pdf import PdfPages

    rows = [[str(i), f"valor_{i}", f"extra_{i}"] for i in range(50)]
    col_labels = ["ID", "Valor", "Extra"]

    with tempfile.TemporaryDirectory() as tmpdir:
        pdf_path = Path(tmpdir) / "test_table.pdf"
        with PdfPages(str(pdf_path)) as pdf:
            render_table_page_pdfpages(pdf, "Test Tabla", rows, col_labels, max_rows=28)

        assert pdf_path.exists()
        assert pdf_path.stat().st_size > 0

        # Verify 2 pages were generated by reading PDF metadata
        try:
            from pypdf import PdfReader
            reader = PdfReader(str(pdf_path))
            assert len(reader.pages) == 2
        except ImportError:
            # If pypdf not available, just check file size
            assert pdf_path.stat().st_size > 1000


def test_0_filas_genera_1_pagina_vacia_sin_excepcion():
    """0 filas genera 1 pagina vacia sin excepcion"""
    import sys
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
    from infra.render_table_page_pdfpages import render_table_page_pdfpages
    from matplotlib.backends.backend_pdf import PdfPages

    with tempfile.TemporaryDirectory() as tmpdir:
        pdf_path = Path(tmpdir) / "empty_table.pdf"
        with PdfPages(str(pdf_path)) as pdf:
            render_table_page_pdfpages(pdf, "Vacío", [], ["Col1", "Col2"])

        assert pdf_path.exists()
        assert pdf_path.stat().st_size > 0
