"""Tests para chunk_with_overlap."""

from __future__ import annotations

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from core.chunk_with_overlap import chunk_with_overlap


def test_texto_vacio_retorna_lista_vacia():
    """texto vacio retorna lista vacia"""
    assert chunk_with_overlap("") == []
    assert chunk_with_overlap("   ") == []


def test_una_frase_menor_que_max_chars_produce_1_chunk():
    """una frase menor que max_chars produce 1 chunk"""
    text = "Esta es una frase corta."
    chunks = chunk_with_overlap(text, max_chars=500, overlap_sentences=0)
    assert len(chunks) == 1
    assert chunks[0]["text"] == text


def test_multiples_frases_producen_N_chunks_con_overlap():
    """multiples frases producen N chunks con overlap"""
    # 3 frases de ~30 chars c/u, max_chars=60 -> al menos 2 chunks
    text = "Primera frase larga aqui. Segunda frase larga aqui. Tercera frase larga aqui."
    chunks = chunk_with_overlap(text, max_chars=55, overlap_sentences=1)
    assert len(chunks) >= 2
    # Cada chunk tiene texto no vacio
    for c in chunks:
        assert c["text"].strip()
        assert len(c["sentences"]) > 0


def test_frase_mas_larga_que_max_chars_no_bucle_infinito():
    """frase mas larga que max_chars se incluye sin bucle infinito"""
    long_sentence = "A" * 2000 + "."
    chunks = chunk_with_overlap(long_sentence, max_chars=100, overlap_sentences=0)
    # Debe terminar (no bucle infinito) y producir exactamente 1 chunk
    assert len(chunks) == 1
    assert chunks[0]["text"] == long_sentence.strip()


def test_overlap_0_no_duplica_frases():
    """overlap=0 no duplica frases entre chunks"""
    text = "Primera frase aqui completa. Segunda frase aqui completa. Tercera frase aqui completa."
    chunks = chunk_with_overlap(text, max_chars=50, overlap_sentences=0)
    # Recolectar todas las frases de todos los chunks
    all_sents = [s for c in chunks for s in c["sentences"]]
    # Con overlap=0 ninguna frase debe aparecer dos veces
    assert len(all_sents) == len(set(all_sents))


def test_overlap_2_el_chunk_N_mas_1_empieza_con_ultimas_2_frases_del_N():
    """overlap=2 el chunk N+1 empieza con las 2 ultimas frases del chunk N"""
    # 5 frases cortas, max_chars=80 para forzar al menos 2 chunks
    text = (
        "Frase uno aqui. "
        "Frase dos aqui. "
        "Frase tres aqui. "
        "Frase cuatro aqui. "
        "Frase cinco aqui."
    )
    chunks = chunk_with_overlap(text, max_chars=80, overlap_sentences=2)
    if len(chunks) >= 2:
        prev_tail = chunks[0]["sentences"][-2:]
        next_head = chunks[1]["sentences"][:2]
        assert prev_tail == next_head
