"""
test_graph_first_class.py
-------------------------
Verification test for the "Graph as First-Class Citizen" refactor.
Ensures that Memory can operate with an InMemoryGraphStore and perform multi-hop reasoning.
"""
# nosec B101 - asserts are intentional in test files

import networkx as nx
import numpy as np
import sys
from hieromem_core.memory import Memory
from hieromem_core.persistence.in_memory_graph_store import InMemoryGraphStore
from hieromem_core.encoder import Encoder, EncoderConfig


def get_stub_encoder():
    config = EncoderConfig(model_name="stub-hash", backend="stub")
    return Encoder(config)


def test_graph_enablement():
    """Verify that graph store is correctly wired into Memory."""
    store = InMemoryGraphStore()

    print(f"Memory module file: {sys.modules['hieromem_core.memory'].__file__}")

    memory = Memory(store=store, debug=True, encoder=get_stub_encoder())

    # Check what Memory sees
    print(f"Memory.graph_store: {memory.graph_store}")

    stats = memory.stats()
    print("Stats:", stats)

    if "error" in stats["graph_store"]:
        print("Graph Store Error:", stats["graph_store"]["error"])

    assert memory.graph_store is not None, "Memory failed to recognize GraphStore"  # nosec B101
    assert isinstance(memory.graph_store, InMemoryGraphStore)  # nosec B101
    assert stats["graph_store"]["backend"] == "networkx"  # nosec B101


def test_multi_hop_reasoning_in_memory():
    """
    Test deterministic 2-hop reasoning using InMemoryGraphStore.
    """
    store = InMemoryGraphStore()
    memory = Memory(store=store, Nmax=10, encoder=get_stub_encoder(), debug=True)

    # Reset conversation to prevent TURN_FOLLOWS edges from being created
    memory.reset_conversation()

    # 1. Insert Episode 1: Alice knows Bob
    G1 = nx.DiGraph()
    G1.add_edge("Alice", "Bob", relation="knows", trust=0.9)
    ep1 = memory.insert(np.zeros(4), G1, meta={"id": "ep1"})

    # Reset again between episodes to prevent TURN_FOLLOWS edges
    memory.reset_conversation()

    # 2. Insert Episode 2: Bob knows Charlie
    G2 = nx.DiGraph()
    G2.add_edge("Bob", "Charlie", relation="knows", trust=0.8)
    memory.insert(np.zeros(4), G2, meta={"id": "ep2"})

    # 3. Perform Graph Search from Episode 1 (Alice)
    results = memory.graph_search(ep1.id, depth=2, limit=10)

    found_charlie = False
    for item in results:
        print(f"Found: {item}")
        if item["target"] == "Charlie":
            found_charlie = True

    assert found_charlie, "Graph search failed to find 2-hop relation (Charlie)"  # nosec B101

    # 4. Verify Stats - semantic edges only (no TURN_FOLLOWS since we reset)
    stats = memory.stats()
    assert stats["graph_store"]["edge_count"] == 2  # nosec B101
    assert stats["graph_store"]["node_count"] == 3  # nosec B101


if __name__ == "__main__":
    try:
        test_graph_enablement()
        test_multi_hop_reasoning_in_memory()
        print("All graph verification tests passed!")
    except Exception as e:
        print(f"Test failed with exception: {e}")
        # import traceback
        # traceback.print_exc()
        exit(1)
