"""Tests para fuzzy_merge_adaptive."""

import sys
import os

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

from fuzzy_merge_adaptive import fuzzy_merge_adaptive


def test_left_join_con_typo():
    left = [{"name": "Madrid"}, {"name": "Barclona"}]
    right = [{"name": "Madrid", "cp": "28"}, {"name": "Barcelona", "cp": "08"}]
    result = fuzzy_merge_adaptive(left, right, left_key="name", right_key="name")
    assert len(result) == 2
    scores = [r["match_score"] for r in result]
    assert all(s >= 80 for s in scores), f"Scores bajos: {scores}"
    assert result[0]["cp"] == "28"
    assert result[1]["cp"] == "08"


def test_inner_join_excluye_sin_match():
    left = [{"name": "Madrid"}, {"name": "ZZZinexistente"}]
    right = [{"name": "Madrid", "cp": "28"}]
    result = fuzzy_merge_adaptive(
        left, right, left_key="name", right_key="name",
        thresholds=[90, 80, 70], how="inner"
    )
    assert len(result) == 1
    assert result[0]["fuzzy_match"] == "Madrid"


def test_left_join_sin_match_devuelve_none():
    left = [{"name": "ZZZinexistente"}]
    right = [{"name": "Madrid", "cp": "28"}]
    result = fuzzy_merge_adaptive(
        left, right, left_key="name", right_key="name",
        thresholds=[95], how="left"
    )
    assert len(result) == 1
    assert result[0]["fuzzy_match"] is None
    assert result[0]["match_score"] == 0
    assert result[0]["threshold_used"] is None


def test_threshold_adaptativo():
    left = [{"name": "Bcn"}]
    right = [{"name": "Barcelona", "cp": "08"}]
    result = fuzzy_merge_adaptive(
        left, right, left_key="name", right_key="name",
        thresholds=[90, 80, 70, 60, 50]
    )
    assert len(result) == 1
    # Puede matchear o no segun score, pero threshold_used <= 90
    if result[0]["threshold_used"] is not None:
        assert result[0]["threshold_used"] <= 90


def test_colision_de_claves_usa_sufijos():
    left = [{"name": "Madrid", "info": "left_info"}]
    right = [{"name": "Madrid", "info": "right_info"}]
    result = fuzzy_merge_adaptive(left, right, left_key="name", right_key="name")
    assert len(result) == 1
    assert "info_left" in result[0]
    assert "info_right" in result[0]
    assert result[0]["info_left"] == "left_info"
    assert result[0]["info_right"] == "right_info"
