"""Tests para excel_to_markdown."""

import datetime
import os
import sys
import tempfile

import openpyxl
import pytest

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


def _make_xlsx(sheets: dict, filename: str) -> str:
    """Crea un archivo .xlsx temporal con los sheets dados."""
    wb = openpyxl.Workbook()
    first = True
    for sheet_name, rows in sheets.items():
        if first:
            ws = wb.active
            ws.title = sheet_name
            first = False
        else:
            ws = wb.create_sheet(sheet_name)
        for row in rows:
            ws.append(row)
    path = os.path.join(tempfile.mkdtemp(), filename)
    wb.save(path)
    return path


def test_xlsx_multiples_sheets():
    """xlsx con multiples sheets produce una seccion H2 por sheet."""
    path = _make_xlsx(
        {
            "Ventas": [["Producto", "Precio", "Cantidad"], ["Manzana", 1.5, 100], ["Pera", 2.0, 50]],
            "Resumen": [["Total", "Importe"], ["150", "225.0"]],
        },
        "multi.xlsx",
    )
    result = excel_to_markdown(path)

    assert "## Sheet: Ventas" in result
    assert "## Sheet: Resumen" in result
    assert "Producto" in result
    assert "Manzana" in result
    assert "Total" in result


def test_sheet_vacio():
    """Sheet sin filas produce nota de sheet vacio."""
    path = _make_xlsx({"Vacio": []}, "empty.xlsx")
    result = excel_to_markdown(path)

    assert "## Sheet: Vacio" in result
    assert "empty sheet" in result


def test_sheet_truncado():
    """Sheet con mas filas que max_rows_per_sheet se trunca con nota."""
    rows = [["col"]] + [[str(i)] for i in range(20)]
    path = _make_xlsx({"Data": rows}, "big.xlsx")
    result = excel_to_markdown(path, max_rows_per_sheet=5)

    assert "omitted" in result
    # 21 filas totales, 5 mostradas -> 16 omitidas
    assert "16 rows omitted" in result


def test_sheet_con_formulas_data_only():
    """Archivo xlsx abierto con data_only=True muestra valores calculados (o None si no guardados)."""
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "Formulas"
    ws.append(["A", "B", "Suma"])
    ws.append([1, 2, "=A2+B2"])
    path = os.path.join(tempfile.mkdtemp(), "formulas.xlsx")
    wb.save(path)

    result = excel_to_markdown(path)
    assert "## Sheet: Formulas" in result
    # La celda formula puede ser None con data_only=True si no fue guardada con valor
    assert "Suma" in result


def test_xls_legacy_con_fechas():
    """xls legacy: la funcion debe aceptar .xls (via xlrd) y manejar fechas."""
    # Creamos un .xls usando xlwt si disponible, si no lo saltamos
    pytest.importorskip("xlwt", reason="xlwt no disponible para crear .xls de prueba")
    import xlwt

    wb = xlwt.Workbook()
    ws = wb.add_sheet("Fechas")
    ws.write(0, 0, "Nombre")
    ws.write(0, 1, "Fecha")
    ws.write(1, 0, "Evento A")

    date_format = xlwt.XFStyle()
    date_format.num_format_str = "YYYY-MM-DD"
    ws.write(1, 1, datetime.date(2024, 1, 15).toordinal() - 693594, date_format)

    path = os.path.join(tempfile.mkdtemp(), "legacy.xls")
    wb.save(path)

    result = excel_to_markdown(path)
    assert "## Sheet: Fechas" in result
    assert "Evento A" in result


def test_extension_no_soportada():
    """Extension no soportada lanza ValueError."""
    path = os.path.join(tempfile.mkdtemp(), "data.csv")
    with open(path, "w") as f:
        f.write("a,b\n1,2\n")

    with pytest.raises(ValueError, match="Unsupported extension"):
        excel_to_markdown(path)


def test_archivo_no_existe():
    """Archivo inexistente lanza FileNotFoundError."""
    with pytest.raises(FileNotFoundError):
        excel_to_markdown("/tmp/no_existe_para_nada.xlsx")


def test_dimensiones_en_metadata():
    """El markdown incluye dimensiones del sheet."""
    path = _make_xlsx({"Hoja1": [["A", "B"], [1, 2], [3, 4]]}, "dims.xlsx")
    result = excel_to_markdown(path)
    assert "**Dimensions:**" in result
    assert "3 x 2" in result


def test_tabla_markdown_formato():
    """La tabla tiene formato correcto con separador de header."""
    path = _make_xlsx({"Datos": [["Col1", "Col2"], ["val1", "val2"]]}, "fmt.xlsx")
    result = excel_to_markdown(path)
    # Debe tener linea separadora con ---
    assert "| --- |" in result or "| --- | --- |" in result
    assert "Col1" in result
    assert "val1" in result
