"""Tests para extract_text_from_file."""

import os
import sys
import tempfile

import pytest

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


def test_pdf_con_texto_extrae_contenido_correctamente():
    """PDF con texto extrae contenido correctamente."""
    try:
        import fitz
    except ImportError:
        pytest.skip("PyMuPDF no instalado")

    # Create a minimal in-memory PDF using PyMuPDF and write it to a temp file
    doc = fitz.open()
    page = doc.new_page()
    page.insert_text((72, 72), "Hello from PDF")
    with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as f:
        tmp_path = f.name
    try:
        doc.save(tmp_path)
        doc.close()
        result = extract_text_from_file(tmp_path)
        assert "Hello from PDF" in result
    finally:
        os.unlink(tmp_path)


def test_archivo_md_utf8_retorna_contenido():
    """archivo MD UTF-8 retorna contenido."""
    content = "# Titulo\n\nParrafo con texto UTF-8: cafe, senor, japon.\n"
    with tempfile.NamedTemporaryFile(
        suffix=".md", mode="wb", delete=False
    ) as f:
        f.write(content.encode("utf-8"))
        tmp_path = f.name
    try:
        result = extract_text_from_file(tmp_path)
        assert "# Titulo" in result
        assert "cafe" in result
    finally:
        os.unlink(tmp_path)


def test_archivo_txt_latin1_detecta_encoding():
    """archivo TXT latin-1 detecta encoding."""
    content = "Texto en latin-1: cafe, hotel, naive\n"
    with tempfile.NamedTemporaryFile(
        suffix=".txt", mode="wb", delete=False
    ) as f:
        f.write(content.encode("latin-1"))
        tmp_path = f.name
    try:
        result = extract_text_from_file(tmp_path)
        # The word "cafe" or similar should appear in the decoded result
        assert len(result) > 0
        assert "cafe" in result or "caf" in result
    finally:
        os.unlink(tmp_path)


def test_archivo_inexistente_lanza_filenotfounderror():
    """archivo inexistente lanza FileNotFoundError."""
    with pytest.raises(FileNotFoundError):
        extract_text_from_file("/tmp/no_existe_este_archivo_12345.txt")


def test_extension_no_soportada_lanza_valueerror():
    """extension no soportada lanza ValueError."""
    with tempfile.NamedTemporaryFile(suffix=".docx", delete=False) as f:
        f.write(b"fake docx content")
        tmp_path = f.name
    try:
        with pytest.raises(ValueError, match="Unsupported file extension"):
            extract_text_from_file(tmp_path)
    finally:
        os.unlink(tmp_path)
