"""工作流状态存储测试（内存降级模式）."""

import pytest

from src.ai.errors import AIWorkflowNotFoundError
from src.ai.workflow.state_store import WorkflowState, WorkflowStateStore


class TestWorkflowState:
    """WorkflowState dataclass 测试."""

    def test_auto_generate_id(self) -> None:
        """自动生成 workflow_id."""
        state = WorkflowState()
        assert state.workflow_id
        assert state.created_at > 0
        assert state.updated_at > 0

    def test_to_dict(self) -> None:
        """to_dict 序列化."""
        state = WorkflowState(user_id="u-1", topic="数学")
        d = state.to_dict()
        assert d["user_id"] == "u-1"
        assert d["topic"] == "数学"
        assert "questions" in d

    def test_from_dict(self) -> None:
        """from_dict 反序列化."""
        data = {
            "workflow_id": "wf-1",
            "user_id": "u-1",
            "topic": "test",
            "status": "pending",
            "questions": [],
        }
        state = WorkflowState.from_dict(data)
        assert state.workflow_id == "wf-1"
        assert state.user_id == "u-1"

    def test_touch_updates_timestamp(self) -> None:
        """touch() 更新 updated_at."""
        state = WorkflowState()
        old = state.updated_at
        import time
        time.sleep(0.01)
        state.touch()
        assert state.updated_at >= old


class TestWorkflowStateStore:
    """WorkflowStateStore 测试（Redis=None 内存模式）."""

    async def test_create_and_get(self) -> None:
        """创建并查询."""
        store = WorkflowStateStore(redis=None)
        state = WorkflowState(user_id="u-1", topic="数学")
        created = await store.create(state)
        assert created.workflow_id == state.workflow_id
        # 查询
        fetched = await store.get(created.workflow_id)
        assert fetched.user_id == "u-1"
        assert fetched.topic == "数学"

    async def test_get_not_found_raises(self) -> None:
        """查询不存在的工作流抛异常."""
        store = WorkflowStateStore(redis=None)
        with pytest.raises(AIWorkflowNotFoundError):
            await store.get("nonexistent-id")

    async def test_update(self) -> None:
        """更新工作流状态."""
        store = WorkflowStateStore(redis=None)
        state = await store.create(WorkflowState(user_id="u-1"))
        updated = await store.update(
            state.workflow_id,
            status="analyzing",
            topic="updated topic",
        )
        assert updated.status == "analyzing"
        assert updated.topic == "updated topic"

    async def test_delete(self) -> None:
        """删除工作流."""
        store = WorkflowStateStore(redis=None)
        state = await store.create(WorkflowState(user_id="u-1"))
        await store.delete(state.workflow_id)
        with pytest.raises(AIWorkflowNotFoundError):
            await store.get(state.workflow_id)

    async def test_delete_nonexistent_no_error(self) -> None:
        """删除不存在的工作流不抛异常."""
        store = WorkflowStateStore(redis=None)
        await store.delete("nonexistent")  # 不抛异常
