"""Tests for VectorMemory."""

from __future__ import annotations

import uuid

import pytest

from koan.memory.vector import VectorMemory


@pytest.fixture
def memory():
    """Create an ephemeral VectorMemory with a unique collection per test."""
    return VectorMemory(collection_name=f"test_{uuid.uuid4().hex[:8]}")


class TestVectorMemory:
    async def test_store_and_retrieve(self, memory: VectorMemory) -> None:
        await memory.store("Python is great for AI", user_id="u1")
        await memory.store("JavaScript is used for web", user_id="u1")

        results = await memory.retrieve("programming languages", user_id="u1")
        assert len(results) >= 1
        contents = [r.content for r in results]
        assert any("Python" in c for c in contents)

    async def test_user_scoping(self, memory: VectorMemory) -> None:
        await memory.store("Alice likes cats", user_id="alice")
        await memory.store("Bob likes dogs", user_id="bob")

        alice_results = await memory.retrieve("pets", user_id="alice")
        assert all(r.user_id == "alice" for r in alice_results)

        bob_results = await memory.retrieve("pets", user_id="bob")
        assert all(r.user_id == "bob" for r in bob_results)

    async def test_no_user_filter_returns_all(self, memory: VectorMemory) -> None:
        await memory.store("Record A", user_id="u1")
        await memory.store("Record B", user_id="u2")

        results = await memory.retrieve("record")
        assert len(results) >= 2

    async def test_store_returns_record(self, memory: VectorMemory) -> None:
        record = await memory.store("test content", user_id="u1", metadata={"key": "val"})
        assert record.content == "test content"
        assert record.user_id == "u1"
        assert record.id is not None

    async def test_delete(self, memory: VectorMemory) -> None:
        record = await memory.store("deleteme", user_id="u1")
        assert await memory.count() == 1

        await memory.delete(record.id)
        assert await memory.count() == 0

    async def test_count(self, memory: VectorMemory) -> None:
        assert await memory.count() == 0
        await memory.store("one")
        await memory.store("two")
        assert await memory.count() == 2

    async def test_n_results_limit(self, memory: VectorMemory) -> None:
        for i in range(10):
            await memory.store(f"Record number {i}")

        results = await memory.retrieve("record", n_results=3)
        assert len(results) == 3

    async def test_custom_record_id(self, memory: VectorMemory) -> None:
        record = await memory.store("test", record_id="custom-id")
        assert record.id == "custom-id"
