from project_brain.build.relation_resolver import (
    RELATION_EDGE_TYPES,
    RelationResolver,
    calculate_relation_edges,
)
from project_brain.graph.json_store import JsonStore
from project_brain.graph.models import Edge


def _nodes():
    functions = [
        {"id": "fn_target", "type": "function", "name": "target", "calls": []},
        {
            "id": "fn_caller",
            "type": "function",
            "name": "caller",
            "calls": ["target"],
        },
        {
            "id": "fn_test",
            "type": "function",
            "name": "test_target",
            "is_test": True,
            "calls": [],
        },
    ]
    classes = [
        {"id": "cls_base", "type": "class", "name": "Base", "bases": []},
        {
            "id": "cls_child",
            "type": "class",
            "name": "Child",
            "bases": ["Base"],
        },
    ]
    files = [
        {
            "id": "file_caller",
            "type": "file",
            "path": "src/app.py",
            "imports": [{"module": "pkg.target", "symbols": ["target"]}],
        },
        {
            "id": "file_target",
            "type": "file",
            "path": "src/pkg/target.py",
            "imports": [],
        },
    ]
    modules = [
        {"id": "mod_src", "type": "module", "path": "src"},
        {"id": "mod_pkg", "type": "module", "path": "src/pkg"},
    ]
    return functions, classes, files, modules


def test_calculate_relation_edges_from_persisted_facts():
    edges = calculate_relation_edges(*_nodes())
    by_type = {edge_type: [] for edge_type in RELATION_EDGE_TYPES}
    for edge in edges:
        by_type[edge.type].append(edge)

    assert [(edge.source, edge.target) for edge in by_type["CALL"]] == [
        ("fn_caller", "fn_target")
    ]
    assert [(edge.source, edge.target) for edge in by_type["IMPLEMENT"]] == [
        ("cls_child", "cls_base")
    ]
    assert [(edge.source, edge.target) for edge in by_type["TEST"]] == [
        ("fn_test", "fn_target")
    ]
    assert [(edge.source, edge.target) for edge in by_type["DEPEND"]] == [
        ("file_caller", "mod_pkg")
    ]


def test_replace_all_removes_stale_relations_but_preserves_structure(tmp_path):
    store = JsonStore(tmp_path)
    for group in _nodes():
        for node in group:
            store.add_node(node)
    store.add_edge(Edge(
        id="fn_caller->fn_missing:CALL",
        type="CALL",
        source="fn_caller",
        target="fn_missing",
    ))
    store.add_edge(Edge(
        id="mod_src->file_caller:CONTAIN",
        type="CONTAIN",
        source="mod_src",
        target="file_caller",
    ))

    replacements = RelationResolver(store).replace_all()

    assert {edge.id for edge in store.get_all_edges() if edge.type in RELATION_EDGE_TYPES} == {
        edge.id for edge in replacements
    }
    assert not any(edge.target == "fn_missing" for edge in store.get_all_edges())
    assert store.get_edges("mod_src", "CONTAIN", direction="out")

    store.update_node("fn_caller", {"calls": []})
    RelationResolver(store).replace_all()
    assert store.get_edges("fn_caller", "CALL", direction="out") == []


def test_legacy_nodes_without_fact_fields_are_supported():
    edges = calculate_relation_edges(
        [{"id": "fn_old", "type": "function", "name": "old"}],
        [{"id": "cls_old", "type": "class", "name": "Old"}],
        [{"id": "file_old", "type": "file", "path": "old.py"}],
        [],
    )
    assert edges == []


def test_call_resolution_uses_context_and_drops_unresolved_ambiguity():
    functions = [
        {
            "id": "caller_owner",
            "type": "function",
            "name": "caller",
            "class_name": "Service",
            "class_id": "cls_service",
            "file_id": "file_app",
            "module_id": "mod_app",
            "calls": ["work", "imported", "ambiguous"],
        },
        {
            "id": "work_same_owner",
            "type": "function",
            "name": "work",
            "class_name": "Service",
            "class_id": "cls_service",
            "file_id": "file_remote",
            "module_id": "mod_remote",
        },
        {
            "id": "work_same_file",
            "type": "function",
            "name": "work",
            "file_id": "file_app",
            "module_id": "mod_app",
        },
        {
            "id": "imported_right",
            "type": "function",
            "name": "imported",
            "file_id": "file_pkg",
            "module_id": "mod_pkg",
        },
        {
            "id": "imported_wrong",
            "type": "function",
            "name": "imported",
            "file_id": "file_remote",
            "module_id": "mod_remote",
        },
        {"id": "ambiguous_a", "type": "function", "name": "ambiguous"},
        {"id": "ambiguous_b", "type": "function", "name": "ambiguous"},
    ]
    files = [
        {
            "id": "file_app",
            "type": "file",
            "path": "src/app/main.py",
            "imports": [{"module": "pkg.api", "symbols": ["imported"]}],
        },
        {"id": "file_pkg", "type": "file", "path": "src/pkg/api.py"},
        {"id": "file_remote", "type": "file", "path": "src/remote/api.py"},
    ]
    modules = [
        {"id": "mod_app", "type": "module", "path": "src/app"},
        {"id": "mod_pkg", "type": "module", "path": "src/pkg"},
        {"id": "mod_remote", "type": "module", "path": "src/remote"},
    ]

    edges = calculate_relation_edges(functions, [], files, modules)
    targets = {
        edge.properties["name"]: edge.target
        for edge in edges
        if edge.type == "CALL"
    }

    assert targets["work"] == "work_same_owner"
    assert targets["imported"] == "imported_right"
    assert "ambiguous" not in targets


def test_implement_resolution_uses_file_then_import_and_drops_ambiguity():
    classes = [
        {
            "id": "child_local",
            "type": "class",
            "name": "ChildLocal",
            "bases": ["Base"],
            "file_id": "file_child_local",
            "module_id": "mod_app",
        },
        {
            "id": "base_local",
            "type": "class",
            "name": "Base",
            "file_id": "file_child_local",
            "module_id": "mod_app",
        },
        {
            "id": "child_import",
            "type": "class",
            "name": "ChildImport",
            "bases": ["ImportedBase"],
            "file_id": "file_child_import",
            "module_id": "mod_app",
        },
        {
            "id": "base_imported",
            "type": "class",
            "name": "ImportedBase",
            "file_id": "file_pkg",
            "module_id": "mod_pkg",
        },
        {
            "id": "base_not_imported",
            "type": "class",
            "name": "ImportedBase",
            "file_id": "file_other",
            "module_id": "mod_other",
        },
        {"id": "child_ambiguous", "type": "class", "name": "Child", "bases": ["Twin"]},
        {"id": "twin_a", "type": "class", "name": "Twin"},
        {"id": "twin_b", "type": "class", "name": "Twin"},
    ]
    files = [
        {"id": "file_child_local", "type": "file", "path": "src/app/local.py"},
        {
            "id": "file_child_import",
            "type": "file",
            "path": "src/app/imported.py",
            "imports": [{"module": "pkg.base", "symbols": ["ImportedBase"]}],
        },
        {"id": "file_pkg", "type": "file", "path": "src/pkg/base.py"},
        {"id": "file_other", "type": "file", "path": "src/other/base.py"},
    ]
    modules = [
        {"id": "mod_app", "type": "module", "path": "src/app"},
        {"id": "mod_pkg", "type": "module", "path": "src/pkg"},
        {"id": "mod_other", "type": "module", "path": "src/other"},
    ]

    edges = calculate_relation_edges([], classes, files, modules)
    targets = {
        edge.source: edge.target for edge in edges if edge.type == "IMPLEMENT"
    }

    assert targets["child_local"] == "base_local"
    assert targets["child_import"] == "base_imported"
    assert "child_ambiguous" not in targets


def test_receiver_evidence_resolves_calls_types_fields_and_macros():
    functions = [
        {
            "id": "caller",
            "type": "function",
            "name": "run",
            "file_id": "file_app",
            "module_id": "mod_app",
            "params": [{"name": "user", "type": "const api::User &"}],
            "type_bindings": [
                {"name": "user", "type_name": "const api::User &", "source": "parameter"}
            ],
            "references": [
                {
                    "kind": "call", "name": "save", "receiver": "user",
                    "qualified_name": "user.save", "line_start": 3,
                    "byte_start": 20, "byte_end": 31,
                },
                {
                    "kind": "write", "name": "name", "receiver": "user",
                    "qualified_name": "user.name", "line_start": 4,
                    "byte_start": 35, "byte_end": 44,
                },
                {
                    "kind": "macro_call", "name": "TRACE", "line_start": 5,
                    "byte_start": 50, "byte_end": 59,
                },
                {
                    "kind": "call", "name": "LOG", "qualified_name": "LOG",
                    "line_start": 6, "byte_start": 60, "byte_end": 68,
                },
            ],
        },
        {
            "id": "user_save", "type": "function", "name": "save",
            "class_name": "User", "class_id": "user_class",
            "file_id": "file_model", "module_id": "mod_model",
        },
        {
            "id": "other_save", "type": "function", "name": "save",
            "class_name": "Other", "class_id": "other_class",
            "file_id": "file_other", "module_id": "mod_other",
        },
    ]
    classes = [
        {
            "id": "user_class", "type": "class", "name": "User",
            "file_id": "file_model", "module_id": "mod_model",
        },
        {
            "id": "other_class", "type": "class", "name": "Other",
            "file_id": "file_other", "module_id": "mod_other",
        },
    ]
    symbols = [
        {
            "id": "user_name", "type": "symbol", "name": "name",
            "kind": "field", "owner_name": "User", "owner_id": "user_class",
            "file_id": "file_model", "module_id": "mod_model",
        },
        {
            "id": "other_name", "type": "symbol", "name": "name",
            "kind": "field", "owner_name": "Other", "owner_id": "other_class",
            "file_id": "file_other", "module_id": "mod_other",
        },
        {
            "id": "trace_macro", "type": "symbol", "name": "TRACE",
            "kind": "macro", "file_id": "file_app", "module_id": "mod_app",
        },
        {
            "id": "log_macro", "type": "symbol", "name": "LOG",
            "kind": "function_macro", "file_id": "file_app", "module_id": "mod_app",
        },
    ]
    files = [
        {
            "id": "file_app", "type": "file", "path": "src/app/main.cpp",
            "imports": [{"module": "model.user", "symbols": ["User"]}],
        },
        {"id": "file_model", "type": "file", "path": "src/model/user.hpp"},
        {"id": "file_other", "type": "file", "path": "src/other/user.hpp"},
    ]
    modules = [
        {"id": "mod_app", "type": "module", "path": "src/app"},
        {"id": "mod_model", "type": "module", "path": "src/model"},
        {"id": "mod_other", "type": "module", "path": "src/other"},
    ]

    edges = calculate_relation_edges(functions, classes, files, modules, symbols)
    relations = {(edge.type, edge.source, edge.target): edge for edge in edges}

    assert ("CALL", "caller", "user_save") in relations
    assert relations[("CALL", "caller", "user_save")].properties["resolution"] == "receiver_type"
    assert ("CALL", "caller", "other_save") not in relations
    assert ("TYPE_REF", "caller", "user_class") in relations
    assert ("ACCESS", "caller", "user_name") in relations
    assert relations[("ACCESS", "caller", "user_name")].properties["mode"] == "write"
    assert ("ACCESS", "caller", "other_name") not in relations
    assert ("MACRO_CALLS", "caller", "trace_macro") in relations
    assert ("MACRO_CALLS", "caller", "log_macro") in relations


def test_macro_calls_include_nested_macros_and_aggregate_locations():
    functions = [{
        "id": "caller", "type": "function", "name": "run",
        "file_id": "c_file", "references": [
            {"kind": "call", "name": "OUTER", "line_start": 10},
            {"kind": "call", "name": "OUTER", "line_start": 12},
        ],
    }]
    symbols = [
        {
            "id": "outer", "type": "symbol", "kind": "macro", "name": "OUTER",
            "file_id": "c_file", "references": [
                {"kind": "macro_call", "name": "INNER", "line_start": 3},
            ],
        },
        {
            "id": "inner", "type": "symbol", "kind": "macro", "name": "INNER",
            "file_id": "c_file",
        },
    ]
    files = [{"id": "c_file", "type": "file", "path": "macro.c", "language": "c"}]

    edges = calculate_relation_edges(functions, [], files, [], symbols)
    by_pair = {
        (edge.source, edge.target): edge
        for edge in edges if edge.type == "MACRO_CALLS"
    }

    assert by_pair[("caller", "outer")].properties["lines"] == [10, 12]
    assert by_pair[("outer", "inner")].properties["lines"] == [3]


def test_direct_callback_argument_creates_callee_to_callback_call():
    functions = [
        {
            "id": "register_decl", "type": "function", "name": "register_cb",
            "is_definition": False, "file_id": "header", "params": [
                {"name": "cb", "type": "callback_t"},
            ],
        },
        {
            "id": "register_def", "type": "function", "name": "register_cb",
            "is_definition": True, "file_id": "library", "params": [
                {"name": "cb", "type": "callback_t"},
            ],
        },
        {
            "id": "callback", "type": "function", "name": "on_ready",
            "is_definition": True, "file_id": "caller_file",
        },
        {
            "id": "caller", "type": "function", "name": "run",
            "file_id": "caller_file", "references": [{
                "kind": "call", "name": "register_cb", "arguments": ["on_ready"],
                "line_start": 20, "line_end": 21,
            }],
        },
    ]
    symbols = [{
        "id": "callback_type", "type": "symbol", "name": "callback_t",
        "kind": "typedef_function_pointer", "file_id": "header",
    }]
    files = [
        {"id": "header", "type": "file", "path": "api.h", "language": "c"},
        {"id": "library", "type": "file", "path": "api.c", "language": "c"},
        {"id": "caller_file", "type": "file", "path": "main.c", "language": "c"},
    ]

    edges = calculate_relation_edges(functions, [], files, [], symbols)
    callback_edge = next(
        edge for edge in edges
        if edge.type == "CALL"
        and edge.source == "register_def"
        and edge.target == "callback"
    )

    assert callback_edge.properties["resolution"] == "direct_callback_argument"
    assert callback_edge.properties["lines"] == [20, 21]


def test_declaration_definition_resolution_requires_unique_normalized_signature():
    functions = [
        {
            "id": "decl", "type": "function", "name": "save",
            "class_name": "User", "is_definition": False,
            "params": [{"name": "value", "type": "const Payload *"}],
            "file_id": "header", "module_id": "api",
        },
        {
            "id": "definition", "type": "function", "name": "save",
            "class_name": "User", "is_definition": True,
            "params": [{"name": "value", "type": "Payload*"}],
            "file_id": "source", "module_id": "api",
        },
        {
            "id": "overload", "type": "function", "name": "save",
            "class_name": "User", "is_definition": True,
            "params": [{"name": "value", "type": "int"}],
            "file_id": "source", "module_id": "api",
        },
    ]

    edges = calculate_relation_edges(functions, [], [], [])

    assert [
        (edge.source, edge.target)
        for edge in edges if edge.type == "DECLARE"
    ] == [("decl", "definition")]


def test_type_declarations_link_to_unique_definition():
    classes = [
        {
            "id": "decl_public", "type": "class", "name": "Context",
            "kind": "struct", "is_definition": False, "file_id": "public_h",
        },
        {
            "id": "decl_api", "type": "class", "name": "Context",
            "kind": "struct", "is_definition": False, "file_id": "api_h",
        },
        {
            "id": "definition", "type": "class", "name": "Context",
            "kind": "struct", "is_definition": True, "file_id": "private_h",
        },
    ]

    edges = calculate_relation_edges([], classes, [], [])

    assert {
        (edge.source, edge.target)
        for edge in edges if edge.type == "DECLARE"
    } == {
        ("decl_public", "definition"),
        ("decl_api", "definition"),
    }


def test_template_specializations_use_explicit_calls_and_concrete_types():
    functions = [
        {
            "id": "identity", "type": "function", "kind": "function_template",
            "name": "identity", "file_id": "cpp_file",
        },
        {
            "id": "use_identity", "type": "function", "name": "use_identity",
            "file_id": "cpp_file", "references": [{
                "kind": "template_call", "name": "identity",
                "qualified_name": "identity", "line_start": 20,
            }],
        },
        {
            "id": "use_box", "type": "function", "name": "use_box",
            "file_id": "cpp_file", "type_bindings": [{
                "name": "box", "type_name": "Box<int>", "source": "declaration",
            }],
        },
    ]
    classes = [{
        "id": "box", "type": "class", "kind": "class_template",
        "name": "Box", "file_id": "cpp_file",
    }]
    files = [
        {"id": "cpp_file", "type": "file", "path": "template.cpp", "language": "cpp"},
    ]

    edges = calculate_relation_edges(functions, classes, files, [])

    assert {
        (edge.source, edge.target)
        for edge in edges if edge.type == "TEMPLATE_SPECIALIZATION"
    } == {
        ("identity", "use_identity"),
        ("box", "use_box"),
    }


def test_cpp_overrides_require_inheritance_and_normalized_signature():
    functions = [
        {
            "id": "base_int", "type": "function", "name": "run",
            "class_id": "base", "params": [{"name": "value", "type": "int"}],
            "file_id": "cpp_file",
        },
        {
            "id": "base_text", "type": "function", "name": "run",
            "class_id": "base", "params": [{"name": "text", "type": "const char *"}],
            "file_id": "cpp_file",
        },
        {
            "id": "child_int", "type": "function", "name": "run",
            "class_id": "child", "params": [{"name": "number", "type": "int"}],
            "line_start": 9, "file_id": "cpp_file",
        },
    ]
    classes = [
        {"id": "base", "type": "class", "name": "Base", "bases": [], "file_id": "cpp_file"},
        {
            "id": "child", "type": "class", "name": "Child",
            "bases": ["Base"], "file_id": "cpp_file",
        },
    ]
    files = [
        {"id": "cpp_file", "type": "file", "path": "main.cpp", "language": "cpp"},
    ]

    edges = calculate_relation_edges(functions, classes, files, [])

    assert [
        (edge.source, edge.target)
        for edge in edges if edge.type == "OVERRIDES"
    ] == [("base_int", "child_int")]


def test_cross_language_edges_require_explicit_ffi_evidence():
    functions = [
        {
            "id": "rust_decl", "type": "function", "name": "native_save",
            "is_definition": False, "linkage": "C", "file_id": "rust_file",
            "params": [{"name": "value", "type": "i32"}],
        },
        {
            "id": "c_definition", "type": "function", "name": "native_save",
            "is_definition": True, "linkage": "C", "file_id": "c_file",
            "params": [{"name": "value", "type": "int"}],
        },
        {
            "id": "python_caller", "type": "function", "name": "run",
            "file_id": "python_file",
            "type_bindings": [{
                "name": "lib", "type_name": "ctypes.CDLL", "source": "ffi_library",
                "foreign_library": "libnative.so",
            }],
            "references": [{
                "kind": "call", "name": "native_save", "receiver": "lib",
                "line_start": 4, "byte_start": 40, "byte_end": 57,
            }],
        },
        {
            "id": "rust_export", "type": "function", "name": "rust_entry",
            "is_definition": True, "linkage": "C", "file_id": "rust_file",
        },
        {
            "id": "c_caller", "type": "function", "name": "call_rust",
            "file_id": "c_file", "references": [{
                "kind": "call", "name": "rust_entry", "line_start": 8,
            }],
        },
    ]
    files = [
        {"id": "rust_file", "type": "file", "path": "src/lib.rs", "language": "rust"},
        {"id": "c_file", "type": "file", "path": "native/api.c", "language": "c"},
        {"id": "python_file", "type": "file", "path": "app.py", "language": "python"},
    ]

    edges = calculate_relation_edges(functions, [], files, [])
    relations = {(edge.type, edge.source, edge.target) for edge in edges}

    assert ("FFI_BIND", "rust_decl", "c_definition") in relations
    assert ("FFI_CALL", "python_caller", "c_definition") in relations
    assert ("FFI_CALL", "c_caller", "rust_export") in relations
    assert ("CALL", "python_caller", "c_definition") not in relations
    assert ("CALL", "c_caller", "rust_export") not in relations


# ---------------------------------------------------------------------------
# Go structural interface satisfaction
# ---------------------------------------------------------------------------

def _go_nodes(**overrides):
    """Node factory for Go satisfaction tests (shared package mod_store)."""
    defaults = {
        "iface": {
            "id": "iface_node", "type": "class", "name": "Storage",
            "kind": "interface", "bases": [], "file_id": "go_file_a",
            "module_id": "mod_store", "is_definition": True,
        },
        "iface_save": {
            "id": "fn_iface_save", "type": "function", "name": "Save",
            "class_name": "Storage", "module_id": "mod_store",
            "params": [{"name": "key", "type": "string"}],
            "return_type": "error", "is_definition": False,
            "file_id": "go_file_a",
        },
        "struct": {
            "id": "struct_node", "type": "class", "name": "MemoryStore",
            "kind": "struct", "bases": [], "file_id": "go_file_b",
            "module_id": "mod_store", "is_definition": True,
        },
        "struct_save": {
            "id": "fn_struct_save", "type": "function", "name": "Save",
            "class_name": "MemoryStore", "module_id": "mod_store",
            "params": [{"name": "key", "type": "string"}],
            "return_type": "error", "is_definition": True,
            "file_id": "go_file_b",
        },
    }
    nodes = {**defaults, **overrides}
    return nodes


def _go_files():
    return [
        {"id": "go_file_a", "type": "file", "path": "store.go", "language": "go"},
        {"id": "go_file_b", "type": "file", "path": "mem.go", "language": "go"},
    ]


def _relations(edges, edge_type):
    return [(e.source, e.target) for e in edges if e.type == edge_type]


def test_go_struct_satisfies_interface_across_files():
    nodes = _go_nodes()
    edges = calculate_relation_edges(
        [nodes["iface_save"], nodes["struct_save"]],
        [nodes["iface"], nodes["struct"]],
        _go_files(), [],
    )

    assert _relations(edges, "IMPLEMENT") == [("struct_node", "iface_node")]
    assert _relations(edges, "OVERRIDES") == [("fn_iface_save", "fn_struct_save")]
    implement = next(e for e in edges if e.type == "IMPLEMENT")
    assert implement.properties["method"] == "structural_satisfaction"
    assert implement.properties["matched_methods"] == ["Save"]


def test_go_missing_method_does_not_satisfy():
    nodes = _go_nodes()
    nodes["struct_save"]["return_type"] = "error"
    del nodes["struct_save"]
    edges = calculate_relation_edges(
        [nodes["iface_save"]], [nodes["iface"], nodes["struct"]], _go_files(), [],
    )
    assert _relations(edges, "IMPLEMENT") == []


def test_go_param_type_mismatch_does_not_satisfy():
    nodes = _go_nodes()
    nodes["struct_save"]["params"] = [{"name": "key", "type": "int"}]
    edges = calculate_relation_edges(
        [nodes["iface_save"], nodes["struct_save"]],
        [nodes["iface"], nodes["struct"]],
        _go_files(), [],
    )
    assert _relations(edges, "IMPLEMENT") == []


def test_go_return_type_mismatch_does_not_satisfy():
    nodes = _go_nodes()
    nodes["struct_save"]["return_type"] = "int"
    edges = calculate_relation_edges(
        [nodes["iface_save"], nodes["struct_save"]],
        [nodes["iface"], nodes["struct"]],
        _go_files(), [],
    )
    assert _relations(edges, "IMPLEMENT") == []


def test_go_empty_interface_does_not_attract_all_structs():
    nodes = _go_nodes()
    nodes["iface_save"]["return_type"] = "error"
    # An ``interface{}``-style marker: no method facts at all.
    edges = calculate_relation_edges(
        [nodes["struct_save"]], [nodes["iface"], nodes["struct"]], _go_files(), [],
    )
    assert _relations(edges, "IMPLEMENT") == []


def test_go_embedded_interface_expands_for_satisfaction():
    nodes = _go_nodes()
    reader = {
        "id": "reader_node", "type": "class", "name": "Reader",
        "kind": "interface", "bases": [], "file_id": "go_file_a",
        "module_id": "mod_store", "is_definition": True,
    }
    reader_load = {
        "id": "fn_reader_load", "type": "function", "name": "Load",
        "class_name": "Reader", "module_id": "mod_store",
        "params": [{"name": "key", "type": "string"}],
        "return_type": "error", "is_definition": False,
        "file_id": "go_file_a",
    }
    struct_load = {
        "id": "fn_struct_load", "type": "function", "name": "Load",
        "class_name": "MemoryStore", "module_id": "mod_store",
        "params": [{"name": "key", "type": "string"}],
        "return_type": "error", "is_definition": True,
        "file_id": "go_file_b",
    }
    nodes["iface"]["bases"] = ["Reader"]
    functions = [nodes["iface_save"], reader_load, nodes["struct_save"], struct_load]
    classes = [reader, nodes["iface"], nodes["struct"]]

    edges = calculate_relation_edges(functions, classes, _go_files(), [])

    assert ("struct_node", "iface_node") in _relations(edges, "IMPLEMENT")
    assert ("fn_iface_save", "fn_struct_save") in _relations(edges, "OVERRIDES")
    assert ("fn_reader_load", "fn_struct_load") in _relations(edges, "OVERRIDES")


def test_go_no_cross_language_satisfaction():
    nodes = _go_nodes()
    py_file = {"id": "py_file", "type": "file", "path": "model.py", "language": "python"}
    nodes["struct"]["file_id"] = "py_file"
    edges = calculate_relation_edges(
        [nodes["iface_save"], nodes["struct_save"]],
        [nodes["iface"], nodes["struct"]],
        _go_files() + [py_file], [],
    )
    assert _relations(edges, "IMPLEMENT") == []


def test_go_no_cross_package_satisfaction():
    nodes = _go_nodes()
    other_file = {"id": "go_file_c", "type": "file", "path": "other/mem.go", "language": "go"}
    nodes["struct"]["module_id"] = "mod_other"
    nodes["struct_save"]["module_id"] = "mod_other"
    nodes["struct_save"]["file_id"] = "go_file_c"
    edges = calculate_relation_edges(
        [nodes["iface_save"], nodes["struct_save"]],
        [nodes["iface"], nodes["struct"]],
        _go_files() + [other_file], [],
    )
    assert _relations(edges, "IMPLEMENT") == []


# ---------------------------------------------------------------------------
# Java OVERRIDES via extends/implements
# ---------------------------------------------------------------------------

def _java_nodes():
    return {
        "files": [
            {"id": "java_file", "type": "file", "path": "App.java", "language": "java"},
        ],
        "classes": [
            {"id": "greeter_node", "type": "class", "name": "Greeter",
             "kind": "interface", "bases": [], "file_id": "java_file",
             "module_id": "mod_app"},
            {"id": "app_node", "type": "class", "name": "App",
             "kind": "class", "bases": ["Greeter"], "file_id": "java_file",
             "module_id": "mod_app"},
        ],
        "functions": [
            {"id": "fn_iface_greet", "type": "function", "name": "greet",
             "class_name": "Greeter", "class_id": "greeter_node",
             "module_id": "mod_app",
             "params": [{"name": "who", "type": "String"}],
             "return_type": "void", "is_definition": False,
             "file_id": "java_file"},
            {"id": "fn_app_greet", "type": "function", "name": "greet",
             "class_name": "App", "class_id": "app_node",
             "module_id": "mod_app",
             "params": [{"name": "who", "type": "String"}],
             "return_type": "void", "is_definition": True,
             "file_id": "java_file"},
        ],
    }


def test_java_implements_interface_emits_overrides():
    nodes = _java_nodes()
    edges = calculate_relation_edges(
        nodes["functions"], nodes["classes"], nodes["files"], [],
    )

    assert _relations(edges, "OVERRIDES") == [("fn_iface_greet", "fn_app_greet")]
    # The generic bases loop also yields the class-level IMPLEMENT edge.
    assert ("app_node", "greeter_node") in _relations(edges, "IMPLEMENT")


def test_java_overload_ambiguity_stays_silent():
    nodes = _java_nodes()
    nodes["functions"].extend([
        {"id": "fn_iface_save_a", "type": "function", "name": "save",
         "class_name": "Greeter", "class_id": "greeter_node",
         "module_id": "mod_app",
         "params": [{"name": "path", "type": "List<String>"}],
         "return_type": "void", "is_definition": False,
         "file_id": "java_file"},
        {"id": "fn_iface_save_b", "type": "function", "name": "save",
         "class_name": "Greeter", "class_id": "greeter_node",
         "module_id": "mod_app",
         "params": [{"name": "path", "type": "java.util.List<String>"}],
         "return_type": "void", "is_definition": False,
         "file_id": "java_file"},
        {"id": "fn_app_save", "type": "function", "name": "save",
         "class_name": "App", "class_id": "app_node",
         "module_id": "mod_app",
         "params": [{"name": "path", "type": "List<String>"}],
         "return_type": "void", "is_definition": True,
         "file_id": "java_file"},
    ])

    edges = calculate_relation_edges(
        nodes["functions"], nodes["classes"], nodes["files"], [],
    )

    overrides = _relations(edges, "OVERRIDES")
    assert ("fn_iface_greet", "fn_app_greet") in overrides
    # ``List<String>`` and ``java.util.List<String>`` normalize to the same
    # tail, so the save() match is ambiguous (two interface candidates) and
    # deliberately produces no edge.
    assert all(target != "fn_app_save" for _, target in overrides)


def test_go_pointer_receiver_records_satisfied_via_star_t():
    """含指针接收者方法时, 只有 *T 的方法集含该方法集 (Go spec)."""
    nodes = _go_nodes()
    nodes["struct_save"]["signature"] = (
        "func (s *MemoryStore) Save(key string) error"
    )
    edges = calculate_relation_edges(
        [nodes["iface_save"], nodes["struct_save"]],
        [nodes["iface"], nodes["struct"]],
        _go_files(), [],
    )
    implement = next(e for e in edges if e.type == "IMPLEMENT")
    assert implement.properties["satisfied_via"] == "*T"


def test_go_value_receiver_records_satisfied_via_both():
    """全值接收者方法集: T 与 *T 都满足."""
    nodes = _go_nodes()
    nodes["struct_save"]["signature"] = (
        "func (s MemoryStore) Save(key string) error"
    )
    edges = calculate_relation_edges(
        [nodes["iface_save"], nodes["struct_save"]],
        [nodes["iface"], nodes["struct"]],
        _go_files(), [],
    )
    implement = next(e for e in edges if e.type == "IMPLEMENT")
    assert implement.properties["satisfied_via"] == "T and *T"