"""Tests para pivot."""

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

from pivot import pivot


def test_pivot_basico_con_sum():
    """Pivot basico con sum."""
    rows = [
        {"region": "US", "product": "A", "sales": 10},
        {"region": "US", "product": "B", "sales": 20},
        {"region": "EU", "product": "A", "sales": 15},
    ]
    result = pivot(rows, index="region", columns="product", values="sales")
    assert len(result) == 2
    us = next(r for r in result if r["region"] == "US")
    eu = next(r for r in result if r["region"] == "EU")
    assert us["A"] == 10
    assert us["B"] == 20
    assert eu["A"] == 15
    assert eu["B"] == 0


def test_pivot_con_count_y_mean():
    """Pivot con count y mean."""
    rows = [
        {"region": "US", "product": "A", "sales": 10},
        {"region": "US", "product": "A", "sales": 20},
        {"region": "EU", "product": "A", "sales": 15},
    ]
    result_count = pivot(rows, index="region", columns="product", values="sales", agg="count")
    us_count = next(r for r in result_count if r["region"] == "US")
    assert us_count["A"] == 2

    result_mean = pivot(rows, index="region", columns="product", values="sales", agg="mean")
    us_mean = next(r for r in result_mean if r["region"] == "US")
    assert us_mean["A"] == 15.0


def test_pivot_valores_faltantes_rellenados_con_0():
    """Valores faltantes rellenados con 0."""
    rows = [
        {"region": "US", "product": "A", "sales": 5},
        {"region": "EU", "product": "B", "sales": 8},
    ]
    result = pivot(rows, index="region", columns="product", values="sales")
    us = next(r for r in result if r["region"] == "US")
    eu = next(r for r in result if r["region"] == "EU")
    assert us["B"] == 0
    assert eu["A"] == 0


def test_pivot_una_sola_fila():
    """Una sola fila."""
    rows = [{"region": "US", "product": "A", "sales": 42}]
    result = pivot(rows, index="region", columns="product", values="sales")
    assert len(result) == 1
    assert result[0]["region"] == "US"
    assert result[0]["A"] == 42


def test_pivot_multiples_valores_por_celda_requieren_agregacion():
    """Multiples valores por celda requieren agregacion."""
    rows = [
        {"region": "US", "product": "A", "sales": 10},
        {"region": "US", "product": "A", "sales": 30},
    ]
    result_sum = pivot(rows, index="region", columns="product", values="sales", agg="sum")
    assert result_sum[0]["A"] == 40

    result_min = pivot(rows, index="region", columns="product", values="sales", agg="min")
    assert result_min[0]["A"] == 10

    result_max = pivot(rows, index="region", columns="product", values="sales", agg="max")
    assert result_max[0]["A"] == 30
