"""Tests for MemoryTool — Agent 可调用的记忆操作工具 (U3)."""

from pathlib import Path

import pytest

from agentkit.memory.profile import MemoryStore
from agentkit.tools.memory_tool import MemoryTool


@pytest.fixture
def store(tmp_path: Path) -> MemoryStore:
    return MemoryStore(base_dir=tmp_path)


@pytest.fixture
def tool(store: MemoryStore) -> MemoryTool:
    return MemoryTool(memory_store=store)


class TestMemoryToolAdd:
    """memory_add 操作测试."""

    async def test_add_creates_new_section(self, tool: MemoryTool, store: MemoryStore):
        result = await tool.execute(action="add", file="memory", section="项目信息", content="使用Python和FastAPI")
        assert result["success"] is True
        content = store.get_file("memory").read_section("项目信息")
        assert "Python和FastAPI" in content

    async def test_add_appends_to_existing_section(self, tool: MemoryTool, store: MemoryStore):
        store.get_file("memory").write("## 项目信息\n使用Python")
        result = await tool.execute(action="add", file="memory", section="项目信息", content="还有TypeScript")
        assert result["success"] is True
        content = store.get_file("memory").read_section("项目信息")
        assert "Python" in content
        assert "TypeScript" in content

    async def test_add_to_soul(self, tool: MemoryTool, store: MemoryStore):
        result = await tool.execute(action="add", file="soul", section="爱好", content="编程和阅读")
        assert result["success"] is True
        assert "编程和阅读" in store.get_file("soul").read_section("爱好")


class TestMemoryToolReplace:
    """memory_replace 操作测试."""

    async def test_replace_text_in_section(self, tool: MemoryTool, store: MemoryStore):
        store.get_file("memory").write("## 项目信息\n使用Python\n## 团队\n3人")
        result = await tool.execute(
            action="replace", file="memory", section="项目信息",
            old_text="Python", new_text="Rust"
        )
        assert result["success"] is True
        assert "Rust" in store.get_file("memory").read_section("项目信息")
        assert "3人" in store.get_file("memory").read_section("团队")

    async def test_replace_old_not_found_fails(self, tool: MemoryTool, store: MemoryStore):
        store.get_file("memory").write("## 项目信息\n使用Python")
        result = await tool.execute(
            action="replace", file="memory", section="项目信息",
            old_text="不存在", new_text="新内容"
        )
        assert result["success"] is False
        assert "not found" in result.get("error", "").lower()


class TestMemoryToolRemove:
    """memory_remove 操作测试."""

    async def test_remove_section(self, tool: MemoryTool, store: MemoryStore):
        store.get_file("memory").write("## 项目信息\n使用Python\n## 团队\n3人")
        result = await tool.execute(action="remove", file="memory", section="项目信息")
        assert result["success"] is True
        assert store.get_file("memory").read_section("项目信息") == ""
        assert "3人" in store.get_file("memory").read_section("团队")


class TestMemoryToolRead:
    """memory_read 操作测试."""

    async def test_read_file_content(self, tool: MemoryTool, store: MemoryStore):
        store.get_file("memory").write("## 项目信息\n使用Python")
        result = await tool.execute(action="read", file="memory")
        assert result["success"] is True
        assert "Python" in result["content"]

    async def test_read_empty_file(self, tool: MemoryTool, store: MemoryStore):
        result = await tool.execute(action="read", file="memory")
        assert result["success"] is True
        assert result["content"] == ""


class TestMemoryToolValidation:
    """参数验证测试."""

    async def test_invalid_file_key(self, tool: MemoryTool):
        result = await tool.execute(action="read", file="invalid")
        assert result["success"] is False
        assert "Invalid" in result.get("error", "")

    async def test_invalid_action(self, tool: MemoryTool):
        result = await tool.execute(action="delete_everything", file="memory")
        assert result["success"] is False
        assert "Unknown action" in result.get("error", "")

    async def test_add_respects_capacity(self, tool: MemoryTool, store: MemoryStore):
        # memory file has MEMORY_BUDGET=2200
        long_content = "A" * 3000
        result = await tool.execute(action="add", file="memory", section="测试", content=long_content)
        assert result["success"] is True
        content = store.get_file("memory").read()
        assert len(content) <= 2200
