"""Tests para parse_rebel_output."""

import os
import sys

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

from python.functions.datascience.parse_rebel_output import parse_rebel_output


def test_string_vacio_retorna_lista_vacia():
    assert parse_rebel_output("") == []


def test_string_solo_espacios_retorna_lista_vacia():
    assert parse_rebel_output("   ") == []


def test_un_triplet_completo_retorna_un_dict_con_campos_correctos():
    decoded = "tp_XX<triplet> Pablo Isla <per> Inditex <org> employer"
    result = parse_rebel_output(decoded)
    assert len(result) == 1
    t = result[0]
    assert t["head"] == "Pablo Isla"
    assert t["head_type"] == "per"
    assert t["tail"] == "Inditex"
    assert t["tail_type"] == "org"
    assert t["type"] == "employer"


def test_dos_triplets_retorna_dos_dicts():
    decoded = (
        "tp_XX<triplet> Pablo Isla <per> Inditex <org> employer "
        "<triplet> Arteixo <loc> A Coruna <loc> located in the administrative territorial entity"
    )
    result = parse_rebel_output(decoded)
    assert len(result) == 2
    assert result[0]["head"] == "Pablo Isla"
    assert result[0]["tail"] == "Inditex"
    assert result[1]["head"] == "Arteixo"
    assert result[1]["tail"] == "A Coruna"
    assert "located" in result[1]["type"]


def test_triplet_incompleto_sin_cierre_no_rompe():
    # Solo head span, sin tail ni relacion
    decoded = "tp_XX<triplet> Pablo Isla"
    result = parse_rebel_output(decoded)
    # No hay cierre, puede retornar lista vacia o incompleta pero no rompe
    assert isinstance(result, list)


def test_tokens_angulares_desconocidos_no_lanzan_excepcion():
    # Un tipo desconocido como <unknown_type> no debe romper el parser
    decoded = "<triplet> Entity One <unknown_type> Entity Two <org> some relation"
    result = parse_rebel_output(decoded)
    assert isinstance(result, list)


def test_sin_prefijo_tp_xx_funciona():
    # REBEL monolingue no emite tp_XX
    decoded = "<triplet> Barack Obama <per> United States <org> president of"
    result = parse_rebel_output(decoded)
    assert len(result) == 1
    assert result[0]["head"] == "Barack Obama"
    assert result[0]["tail"] == "United States"
    assert result[0]["type"] == "president of"


def test_strip_tags_s_pad():
    decoded = "<s><pad>tp_XX<triplet> Ana <per> BBVA <org> works at</s>"
    result = parse_rebel_output(decoded)
    assert len(result) == 1
    assert result[0]["head"] == "Ana"
    assert result[0]["tail"] == "BBVA"
