"""Tests para generate_synthetic_eda_folder."""

import os
import statistics

import pandas as pd

from datascience.generate_synthetic_eda_folder import generate_synthetic_eda_folder


def test_genera_ok_y_archivos(tmp_path):
    out = str(tmp_path / "folder")
    res = generate_synthetic_eda_folder(out, n_rows=300, seed=42)
    assert res["status"] == "ok"
    assert res["n_customers"] == 300
    assert res["n_orders"] == 600
    assert res["n_reviews"] == 300
    for key in ("customers", "orders", "reviews"):
        assert os.path.exists(res["files"][key])
    # Relaciones esperadas declaradas.
    rels = {(r["from_table"], r["to_table"]) for r in res["expected_relations"]}
    assert ("orders", "customers") in rels
    assert ("reviews", "customers") in rels


def test_determinismo_mismo_seed(tmp_path):
    out1 = str(tmp_path / "f1")
    out2 = str(tmp_path / "f2")
    generate_synthetic_eda_folder(out1, n_rows=250, seed=11)
    generate_synthetic_eda_folder(out2, n_rows=250, seed=11)
    for name in ("customers.csv", "orders.csv", "reviews.csv"):
        a = open(os.path.join(out1, name), "rb").read()
        b = open(os.path.join(out2, name), "rb").read()
        assert a == b, f"{name} difiere entre dos generaciones con el mismo seed"


def test_seeds_distintos_difieren(tmp_path):
    out1 = str(tmp_path / "f1")
    out2 = str(tmp_path / "f2")
    generate_synthetic_eda_folder(out1, n_rows=250, seed=11)
    generate_synthetic_eda_folder(out2, n_rows=250, seed=12)
    a = open(os.path.join(out1, "customers.csv"), "rb").read()
    b = open(os.path.join(out2, "customers.csv"), "rb").read()
    assert a != b


def test_fk_containment(tmp_path):
    out = str(tmp_path / "folder")
    res = generate_synthetic_eda_folder(out, n_rows=300, seed=42)
    customers = pd.read_csv(res["files"]["customers"])
    orders = pd.read_csv(res["files"]["orders"])
    reviews = pd.read_csv(res["files"]["reviews"])
    cust_ids = set(customers["customer_id"])
    # Todos los customer_id de orders y reviews ⊆ customers.
    assert set(orders["customer_id"]) <= cust_ids
    assert set(reviews["customer_id"]) <= cust_ids
    # customer_id es PK unica en customers.
    assert customers["customer_id"].is_unique
    assert orders["order_id"].is_unique
    assert reviews["review_id"].is_unique


def test_review_text_mediana_palabras(tmp_path):
    out = str(tmp_path / "folder")
    res = generate_synthetic_eda_folder(out, n_rows=300, seed=42)
    reviews = pd.read_csv(res["files"]["reviews"])
    words = [len(str(t).split()) for t in reviews["review_text"].dropna()]
    assert statistics.median(words) >= 20


def test_n_rows_invalido(tmp_path):
    out = str(tmp_path / "folder")
    res = generate_synthetic_eda_folder(out, n_rows=0, seed=42)
    assert res["status"] == "error"
