"""Tests for memory retrieval — keyword search and daily log loading."""

from datetime import date, timedelta

from fliiq.runtime.memory.manager import MemoryManager
from fliiq.runtime.memory.retrieval import load_recent_daily, load_relevant_entities, search_memories


def test_search_finds_keyword(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    mgr.save_memory("MEMORY", "Andy is learning Cantonese.\nHe likes dim sum.")
    results = search_memories(mgr, "Cantonese")
    assert len(results) == 1
    assert results[0].file_name == "MEMORY.md"
    assert "Cantonese" in results[0].line


def test_search_case_insensitive(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    mgr.save_memory("MEMORY", "Fitness goal: lose 15 pounds")
    results = search_memories(mgr, "fitness")
    assert len(results) == 1


def test_search_case_sensitive(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    mgr.save_memory("MEMORY", "Fitness goal: lose 15 pounds")
    results = search_memories(mgr, "fitness", ignore_case=False)
    assert len(results) == 0


def test_search_max_results(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    mgr.save_memory("MEMORY", "\n".join(f"line {i} keyword" for i in range(20)))
    results = search_memories(mgr, "keyword", max_results=5)
    assert len(results) == 5


def test_search_cross_file(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    mgr.save_memory("MEMORY", "keyword here")
    mgr.save_memory("skills/fitness", "keyword there too")
    results = search_memories(mgr, "keyword")
    files = {r.file_name for r in results}
    assert len(files) == 2


def test_search_context_lines(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    mgr.save_memory("MEMORY", "line above\ntarget line\nline below")
    results = search_memories(mgr, "target")
    assert "line above" in results[0].context
    assert "line below" in results[0].context


def test_search_empty_dir(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    results = search_memories(mgr, "anything")
    assert results == []


def test_load_recent_daily(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    today = date.today()
    yesterday = today - timedelta(days=1)
    mgr.save_memory(today.isoformat(), "Today's notes")
    mgr.save_memory(yesterday.isoformat(), "Yesterday's notes")
    result = load_recent_daily(mgr, days=3)
    assert "Today's notes" in result
    assert "Yesterday's notes" in result


def test_load_recent_daily_empty(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    result = load_recent_daily(mgr, days=3)
    assert result == ""


# --- load_relevant_entities tests ---


def test_relevant_entities_name_match(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    mgr.save_entity("people", "norm-chan", "# Norm Chan\n- Co-founder of Simplify Health")
    mgr.save_entity("people", "alice-smith", "# Alice Smith\n- Investor from VC firm")

    result = load_relevant_entities(mgr, "Tell Norm about the launch plan")
    assert "Norm Chan" in result
    # Alice should not appear — no name match and low keyword overlap
    assert "Alice" not in result or result.index("Norm") < result.index("Alice")


def test_relevant_entities_keyword_overlap(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    mgr.save_entity("topics", "tennis-training", "# Tennis Training\n- Working on serve consistency")
    mgr.save_entity("topics", "fliiq-launch", "# Fliiq Launch\n- Q1 target for beta release")

    result = load_relevant_entities(mgr, "How is my tennis serve coming along?")
    assert "Tennis Training" in result


def test_relevant_entities_empty_prompt(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    mgr.save_entity("topics", "anything", "# Anything\n- content")

    result = load_relevant_entities(mgr, "")
    assert result == ""


def test_relevant_entities_no_match(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    mgr.save_entity("topics", "cooking", "# Cooking\n- Italian recipes")

    result = load_relevant_entities(mgr, "deploy kubernetes cluster")
    assert result == ""


def test_relevant_entities_respects_max_chars(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    mgr.ensure_dirs()
    # Create many entities with overlapping keywords
    for i in range(20):
        mgr.save_entity("topics", f"topic-{i}", f"# Topic {i}\n- keyword shared content")

    result = load_relevant_entities(mgr, "keyword shared content", max_chars=500)
    assert len(result) <= 600  # Some tolerance for headers


def test_relevant_entities_no_dirs(tmp_path):
    mgr = MemoryManager(tmp_path / "memory")
    # Don't create dirs at all
    result = load_relevant_entities(mgr, "anything")
    assert result == ""
