import pytest

from blends.stack import (
    MultiFileResolutionRequest,
    resolve_definitions_multi_file,
)
from blends.stack.forward_stitcher import ForwardStitcherConfig
from test.stack.test_helpers import (
    QUERY_MAX_PHASES,
    QUERY_MAX_WORK,
    find_symbol_nodes,
    setup_multi_file_database,
)

_FH_PKG = 1
_FH_CONSUMER = 2

_CONFIG = ForwardStitcherConfig(
    max_phases=QUERY_MAX_PHASES,
    max_total_work=QUERY_MAX_WORK,
)


@pytest.mark.blends_test_group("stack_unittesting")
def test_init_file_cross_file_resolution() -> None:
    views, database = setup_multi_file_database(
        {"pkg/__init__.py": _FH_PKG, "pkg_consumer.py": _FH_CONSUMER}
    )
    view = views[_FH_CONSUMER]
    symbol_id = view.symbols.symbol_to_id.get("EXPORTED_VALUE")
    assert symbol_id is not None
    ref_nodes = find_symbol_nodes(view, symbol_id=symbol_id, is_definition=False)
    assert ref_nodes

    result = resolve_definitions_multi_file(
        view,
        database,
        request=MultiFileResolutionRequest(
            file_handle=_FH_CONSUMER,
            ref_node_index=ref_nodes[0],
            config=_CONFIG,
        ),
        views=views,
    )

    assert isinstance(result, list)
    pkg_nodes = [node_index for fh, node_index in result if fh == _FH_PKG]
    assert pkg_nodes, (
        f"expected resolution to pkg/__init__.py (fh={_FH_PKG}), got {[fh for fh, _ in result]}"
    )

    pkg_view = views[_FH_PKG]
    pkg_symbol_id = pkg_view.symbols.symbol_to_id.get("EXPORTED_VALUE")
    assert pkg_symbol_id is not None
    def_nodes = find_symbol_nodes(pkg_view, symbol_id=pkg_symbol_id, is_definition=True)
    assert any(n in def_nodes for n in pkg_nodes), (
        f"resolved node(s) {pkg_nodes} are not definition nodes for EXPORTED_VALUE"
    )
