"""Tests for session filtering in OpenclawHookAdapter.remember()."""
from __future__ import annotations

import asyncio
from typing import Any, Dict, List, Optional
from unittest.mock import AsyncMock, MagicMock, patch

import pytest


def _make_adapter():
    """Import and return a minimally-configured OpenClawCortexPlugin."""
    from cortex.integrations.openclaw_plugin import OpenClawCortexPlugin

    adapter = OpenClawCortexPlugin.__new__(OpenClawCortexPlugin)
    # Patch internal state so it doesn't try to connect
    adapter._plugin = None
    adapter._config = MagicMock()
    return adapter


CONVERSATION = [
    {"role": "user", "content": "hello"},
    {"role": "assistant", "content": "hi"},
]


@pytest.mark.asyncio
async def test_subagent_session_is_filtered():
    adapter = _make_adapter()
    result = await adapter.remember(
        CONVERSATION,
        metadata={"session_id": "agent:main:subagent:abc123"},
    )
    assert result == {"ok": True, "skipped": True, "reason": "noisy_session"}


@pytest.mark.asyncio
async def test_cron_session_is_filtered():
    adapter = _make_adapter()
    result = await adapter.remember(
        CONVERSATION,
        metadata={"session_id": "agent:main:cron:heartbeat"},
    )
    assert result == {"ok": True, "skipped": True, "reason": "noisy_session"}


@pytest.mark.asyncio
async def test_isolated_session_is_filtered():
    adapter = _make_adapter()
    result = await adapter.remember(
        CONVERSATION,
        metadata={"session_id": "agent:main:isolated:xyz"},
    )
    assert result == {"ok": True, "skipped": True, "reason": "noisy_session"}


@pytest.mark.asyncio
async def test_main_session_passes_through():
    """Main session IDs must NOT be filtered — they should reach the plugin."""
    adapter = _make_adapter()
    # _ensure_plugin returns None → remember returns ok=False but NOT skipped
    with patch.object(adapter, "_ensure_plugin", return_value=None):
        result = await adapter.remember(
            CONVERSATION,
            metadata={"session_id": "agent:main:main"},
        )
    # Should NOT be the noisy-session short-circuit
    assert result.get("skipped") is not True


@pytest.mark.asyncio
async def test_no_metadata_passes_through():
    """Missing metadata must not cause an error and must not be filtered."""
    adapter = _make_adapter()
    with patch.object(adapter, "_ensure_plugin", return_value=None):
        result = await adapter.remember(CONVERSATION, metadata=None)
    assert result.get("skipped") is not True


@pytest.mark.asyncio
async def test_empty_session_id_passes_through():
    adapter = _make_adapter()
    with patch.object(adapter, "_ensure_plugin", return_value=None):
        result = await adapter.remember(
            CONVERSATION,
            metadata={"session_id": ""},
        )
    assert result.get("skipped") is not True
