"""Tests para melt."""

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

from melt import melt


def test_melt_basico():
    """Melt basico."""
    rows = [{"region": "US", "q1": 10, "q2": 20}]
    result = melt(rows, id_vars=["region"], value_vars=["q1", "q2"])
    assert len(result) == 2
    assert result[0] == {"region": "US", "variable": "q1", "value": 10}
    assert result[1] == {"region": "US", "variable": "q2", "value": 20}


def test_melt_multiples_id_vars():
    """Multiples id_vars."""
    rows = [{"region": "US", "year": 2023, "q1": 10, "q2": 20}]
    result = melt(rows, id_vars=["region", "year"], value_vars=["q1", "q2"])
    assert len(result) == 2
    assert result[0]["region"] == "US"
    assert result[0]["year"] == 2023
    assert result[0]["variable"] == "q1"
    assert result[0]["value"] == 10
    assert result[1]["variable"] == "q2"
    assert result[1]["value"] == 20


def test_melt_value_vars_none_derrite_todas_las_columnas_no_id():
    """value_vars None derrite todas las columnas no-id."""
    rows = [{"id": 1, "a": 10, "b": 20, "c": 30}]
    result = melt(rows, id_vars=["id"])
    assert len(result) == 3
    vars_found = {r["variable"] for r in result}
    assert vars_found == {"a", "b", "c"}
    values_found = {r["value"] for r in result}
    assert values_found == {10, 20, 30}


def test_melt_fila_con_campo_faltante_en_value_vars():
    """Fila con campo faltante en value_vars."""
    rows = [{"region": "US", "q1": 10}]  # q2 no existe
    result = melt(rows, id_vars=["region"], value_vars=["q1", "q2"])
    assert len(result) == 2
    q2_row = next(r for r in result if r["variable"] == "q2")
    assert q2_row["value"] is None
