"""
Tests for ReasoningChain creation and storage.
"""

from hieromem_core.reasoning import ReasoningChain
from hieromem_core.symbolic import ScoredPath
from hieromem_core.memory import Memory


def test_reasoning_chain_creation():
    path = ScoredPath(
        path=["A", "B", "C"],
        score=0.8,
        trust_score=0.9,
        semantic_score=1.0,
        length_penalty=0.81,
        explanation="A leads to B then leads to C"
    )
    chain = ReasoningChain.from_path(path, query_text="How to get from A to C?", source_episodes=["ep1", "ep2"])

    assert chain.query_context == "How to get from A to C?"  # nosec B101
    assert chain.scored_path.score == 0.8  # nosec B101
    assert "ep1" in chain.source_episodes  # nosec B101

    text = chain.to_text()
    assert "Reasoning Chain Explanation" in text  # nosec B101
    assert "Final Score: 0.80" in text  # nosec B101


def test_reasoning_chain_persistence(monkeypatch):
    # Mock EncoderFactory to avoid loading real models
    class MockEncoder:
        def encode(self, text):
            # Return dummy vector of correct dimension (e.g. 768 or just 3 for tests)
            import numpy as np
            return np.array([0.1, 0.2, 0.3], dtype=np.float32)

    class MockFactory:
        @staticmethod
        def get_encoder(name):
            return MockEncoder()

    monkeypatch.setattr("hieromem_core.encoders.EncoderFactory", MockFactory)

    # Mock memory with minimal config
    mem = Memory(Nmax=100)

    path = ScoredPath(
        path=["X", "Y"],
        score=0.9,
        trust_score=1.0,
        semantic_score=1.0,
        length_penalty=0.9,
        explanation="X -> Y"
    )
    chain = ReasoningChain.from_path(path, query_text="X to Y?")

    # Add to memory
    ep = mem.add_reasoning_chain(chain)

    assert ep is not None  # nosec B101
    assert ep.meta["type"] == "reasoning_chain"  # nosec B101
    assert ep.meta["episode_type"] == "derived"  # nosec B101
    assert ep.meta["query"] == "X to Y?"  # nosec B101
    assert ep.meta["score"] == 0.9  # nosec B101
    assert ep.meta["path"] == ["X", "Y"]  # nosec B101

    # Retrieve it back
    assert ep in mem.episodes  # nosec B101
