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

import tempfile
from pathlib import Path

import pytest


def test_lee_csv_utf_8_correctamente():
    """lee csv utf-8 correctamente"""
    import sys
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
    from core.safe_read_csv_fallback import safe_read_csv_fallback

    with tempfile.TemporaryDirectory() as tmpdir:
        csv_path = Path(tmpdir) / "test_utf8.csv"
        csv_path.write_text("nombre,valor\nAña,42\nBéta,99\n", encoding="utf-8")

        df = safe_read_csv_fallback(csv_path)
        assert df.shape == (2, 2)
        assert list(df.columns) == ["nombre", "valor"]
        assert df["nombre"].tolist() == ["Aña", "Béta"]


def test_lee_csv_latin_1_con_fallback():
    """lee csv latin-1 con fallback"""
    import sys
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
    from core.safe_read_csv_fallback import safe_read_csv_fallback

    with tempfile.TemporaryDirectory() as tmpdir:
        csv_path = Path(tmpdir) / "test_latin1.csv"
        # Write latin-1 encoded CSV (ñ, é are 0xF1, 0xE9 in latin-1)
        csv_path.write_bytes("nombre,valor\nMad\xf1id,10\nC\xe9ntro,20\n".encode("latin-1"))

        df = safe_read_csv_fallback(csv_path)
        assert df.shape == (2, 2)
        assert "Mad" in df["nombre"].iloc[0]
        assert df["valor"].tolist() == [10, 20]
