"""Tests para infer_json_rows_schema."""
import sys
import os

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

from core.infer_json_rows_schema import infer_json_rows_schema


def test_lista_de_dicts_directa_retorna_root_path_dolar():
    data = [{"a": 1, "b": "x"}]
    result = infer_json_rows_schema(data)
    assert result["root_path"] == "$"
    assert len(result["fields"]) == 2
    fields_by_name = {f["name"]: f for f in result["fields"]}
    assert fields_by_name["a"]["type"] == "int"
    assert fields_by_name["b"]["type"] == "string"
    assert result["count"] == 1


def test_dict_con_clave_results_retorna_root_path_dolar_punto_results():
    data = {"results": [{"id": 42, "label": "foo"}]}
    result = infer_json_rows_schema(data)
    assert result["root_path"] == "$.results"
    assert result["count"] == 1
    fields_by_name = {f["name"]: f for f in result["fields"]}
    assert fields_by_name["id"]["type"] == "int"
    assert fields_by_name["label"]["type"] == "string"


def test_input_vacio_retorna_schema_vacio():
    assert infer_json_rows_schema({}) == {"root_path": "", "fields": [], "count": 0}
    assert infer_json_rows_schema([]) == {"root_path": "", "fields": [], "count": 0}


def test_tipos_varios():
    data = [{"s": "hello", "i": 1, "f": 1.5, "b": True, "n": None, "arr": [1], "obj": {"x": 1}}]
    result = infer_json_rows_schema(data)
    by_name = {f["name"]: f["type"] for f in result["fields"]}
    assert by_name["s"] == "string"
    assert by_name["i"] == "int"
    assert by_name["f"] == "float"
    assert by_name["b"] == "bool"
    assert by_name["n"] == "null"
    assert by_name["arr"] == "array"
    assert by_name["obj"] == "object"


def test_sample_truncado():
    long_val = "x" * 100
    data = [{"field": long_val}]
    result = infer_json_rows_schema(data)
    assert len(result["fields"][0]["sample"]) == 80


if __name__ == "__main__":
    test_lista_de_dicts_directa_retorna_root_path_dolar()
    test_dict_con_clave_results_retorna_root_path_dolar_punto_results()
    test_input_vacio_retorna_schema_vacio()
    test_tipos_varios()
    test_sample_truncado()
    print("All tests passed.")
