"""Tests para aggregate_extraction_results."""

from __future__ import annotations

import os
import sys
from collections import Counter

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

from core.aggregate_extraction_results import aggregate_extraction_results


def test_lista_vacia_retorna_entities_y_relations_vacios():
    """lista vacia retorna entities vacio y relations vacio"""
    result = aggregate_extraction_results([])
    assert result["entities"] == {}
    assert result["relations"] == Counter()


def test_resultado_unico_se_agrega_correctamente():
    """resultado unico se agrega correctamente"""
    r = [
        {
            "entities": {"person": ["Pablo Isla"], "organization": ["Inditex"]},
            "relation_extraction": {"ceo_of": [("Pablo Isla", "Inditex")]},
        }
    ]
    result = aggregate_extraction_results(r)
    assert ("person", "pablo isla") in result["entities"]
    assert ("organization", "inditex") in result["entities"]
    assert result["entities"][("person", "pablo isla")]["count"] == 1
    assert result["relations"][("Pablo Isla", "ceo_of", "Inditex")] == 1


def test_dos_resultados_con_solapamiento_acumulan_counts():
    """dos resultados con solapamiento acumulan counts"""
    r = [
        {
            "entities": {"person": ["Pablo Isla"], "organization": ["Inditex"]},
            "relation_extraction": {"ceo_of": [("Pablo Isla", "Inditex")]},
        },
        {
            "entities": {"person": ["Pablo Isla"], "organization": ["Inditex"]},
            "relation_extraction": {"ceo_of": [("Pablo Isla", "Inditex")]},
        },
    ]
    result = aggregate_extraction_results(r)
    assert result["entities"][("person", "pablo isla")]["count"] == 2
    assert result["relations"][("Pablo Isla", "ceo_of", "Inditex")] == 2


def test_entidades_deduplicen_case_insensitive():
    """entidades se deduplicien case-insensitive"""
    r = [
        {"entities": {"person": ["Pablo Isla"]}, "relation_extraction": {}},
        {"entities": {"person": ["pablo isla"]}, "relation_extraction": {}},
    ]
    result = aggregate_extraction_results(r)
    # Ambas van a la misma key (person, pablo isla)
    assert ("person", "pablo isla") in result["entities"]
    assert result["entities"][("person", "pablo isla")]["count"] == 2
    # Solo una key para pablo isla
    pablo_keys = [k for k in result["entities"] if k[1] == "pablo isla"]
    assert len(pablo_keys) == 1
