"""Tests para read_file_with_encoding."""

import os
import sys
import tempfile
from pathlib import Path

import pytest

_HERE = Path(__file__).parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))

from read_file_with_encoding import read_file_with_encoding  # noqa: E402


def _write_bytes(content: bytes) -> str:
    """Escribe bytes a un archivo temporal y retorna su path."""
    fd, path = tempfile.mkstemp()
    try:
        os.write(fd, content)
    finally:
        os.close(fd)
    return path


def test_archivo_utf8():
    texto = "Hola mundo con acentos: áéíóú"
    path = _write_bytes(texto.encode("utf-8"))
    try:
        result = read_file_with_encoding(path)
        assert result == texto
    finally:
        os.unlink(path)


def test_archivo_utf8_con_bom():
    texto = "Contenido con BOM"
    path = _write_bytes(texto.encode("utf-8-sig"))
    try:
        # Usando utf-8-sig explicitamente para que el BOM sea eliminado
        result = read_file_with_encoding(path, encodings=["utf-8-sig"])
        assert result == texto
    finally:
        os.unlink(path)


def test_archivo_latin1():
    texto = "Texto en Latin-1: café"
    path = _write_bytes(texto.encode("latin-1"))
    try:
        result = read_file_with_encoding(path)
        assert result == texto
    finally:
        os.unlink(path)


def test_archivo_binario_falla():
    # Bytes que no son validos en ningun encoding de texto comun
    path = _write_bytes(bytes([0x80, 0x81, 0x82, 0x83, 0xFF, 0xFE, 0x00, 0x01]))
    try:
        with pytest.raises(ValueError, match="Unable to decode file"):
            # Forzar solo encodings estrictos para que falle con binario puro
            read_file_with_encoding(path, encodings=["utf-8", "utf-8-sig"])
    finally:
        os.unlink(path)


def test_encodings_personalizados():
    texto = "Windows text: Ñoño"
    path = _write_bytes(texto.encode("cp1252"))
    try:
        result = read_file_with_encoding(path, encodings=["cp1252"])
        assert result == texto
    finally:
        os.unlink(path)


def test_archivo_no_existe():
    with pytest.raises(FileNotFoundError):
        read_file_with_encoding("/tmp/archivo_que_no_existe_12345.txt")
