import json
from pathlib import Path


def test_qa_similarity_creates_ledger(tmp_path, monkeypatch):
    # Prepare monkeypatched database.db
    class DummyDB:
        def sample_motions(self, sample_size):
            assert sample_size == 2
            return [1, 2]

        def get_cached_similarities(self, motion_id, top_k):
            # return deterministic neighbors
            return [
                {"id": motion_id * 10 + i, "score": 1.0 - i * 0.1} for i in range(top_k)
            ]

    dummy = DummyDB()

    # Monkeypatch the database module to provide .db — use monkeypatch.setitem
    # so the override is active for this test and auto-reverts after.
    import types

    fake_db_module = types.SimpleNamespace(db=dummy)

    import sys

    monkeypatch.setitem(sys.modules, "database", fake_db_module)

    # Ensure thoughts/ledgers inside tmp_path
    base = tmp_path
    (base / "thoughts" / "ledgers").mkdir(parents=True)

    # Monkeypatch cwd so ledger writes to tmp_path/thoughts
    monkeypatch.chdir(base)

    from scripts.qa_similarity import main

    summary = main(db_path=":memory:", sample_size=2, top_k=3)

    assert summary["sample_size"] == 2
    assert summary["top_k"] == 3
    assert 1 in summary["motions"]
    assert 2 in summary["motions"]

    ledger_path = Path(summary["ledger_path"])
    assert ledger_path.exists()

    data = json.loads(ledger_path.read_text(encoding="utf-8"))
    assert "motions" in data
    assert len(data["motions"]) == 2
