"""Tests para trim_ax_tree."""

import sys
import os

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

from trim_ax_tree import trim_ax_tree


def _node(node_id: str, role: str, name: str = "", child_ids=None, ignored: bool = False) -> dict:
    return {
        "nodeId": node_id,
        "ignored": ignored,
        "role": {"value": role},
        "name": {"value": name},
        "childIds": child_ids or [],
    }


def test_descarta_nodo_generic_sin_name_ni_childIds():
    nodes = [
        _node("1", "RootWebArea", "", ["2"]),
        _node("2", "generic", "", []),
    ]
    result = trim_ax_tree(nodes)
    ids = [n["nodeId"] for n in result]
    assert "2" not in ids, f"generic sin name/childIds debe descartarse, got {ids}"


def test_mantiene_nodo_button_con_name():
    nodes = [
        _node("1", "RootWebArea", "", ["2"]),
        _node("2", "button", "Click me", []),
    ]
    result = trim_ax_tree(nodes)
    ids = [n["nodeId"] for n in result]
    assert "2" in ids, f"button con name debe mantenerse, got {ids}"


def test_descarta_nodo_ignored():
    nodes = [
        _node("1", "RootWebArea", "", ["2"]),
        _node("2", "button", "Visible", [], ignored=True),
    ]
    result = trim_ax_tree(nodes)
    ids = [n["nodeId"] for n in result]
    assert "2" not in ids, f"nodo ignored debe descartarse, got {ids}"


def test_descarta_StaticText_con_name_vacio():
    nodes = [
        _node("1", "RootWebArea", "", ["2", "3"]),
        _node("2", "StaticText", "", []),
        _node("3", "StaticText", "Hola", []),
    ]
    result = trim_ax_tree(nodes)
    ids = [n["nodeId"] for n in result]
    assert "2" not in ids, f"StaticText vacio debe descartarse, got {ids}"
    assert "3" in ids, f"StaticText con name debe mantenerse, got {ids}"


def test_colapsa_nodo_con_un_hijo_del_mismo_role():
    nodes = [
        _node("1", "RootWebArea", "", ["2"]),
        _node("2", "group", "", ["3"]),
        _node("3", "group", "", ["4"]),
        _node("4", "button", "OK", []),
    ]
    result = trim_ax_tree(nodes)
    ids = [n["nodeId"] for n in result]
    # Nodo 2 y 3 tienen mismo role y uno tiene 1 solo hijo — deben colapsar
    assert "4" in ids, f"button debe estar presente, got {ids}"
    # Tras colapso, el nodo raiz group debe tener childIds apuntando a button
    root_group = next((n for n in result if n["nodeId"] in ("2", "3")), None)
    if root_group:
        assert "4" in root_group.get("childIds", []), \
            f"grupo colapsado debe tener button como hijo, got {root_group}"


if __name__ == "__main__":
    test_descarta_nodo_generic_sin_name_ni_childIds()
    test_mantiene_nodo_button_con_name()
    test_descarta_nodo_ignored()
    test_descarta_StaticText_con_name_vacio()
    test_colapsa_nodo_con_un_hijo_del_mismo_role()
    print("All tests passed.")
