"""ResponseMgr 与 TaskFlowMgr 的清理/插入/查找。"""

from __future__ import annotations

import time

import pytest

from linksoul_agentsdk.active import TaskFlowRequest
from linksoul_agentsdk.agent_sdk import AgentSdk
from linksoul_agentsdk.mgr.callback_type_mgr import AgentSdkCallbackTypeMgr
from linksoul_agentsdk.mgr.response_mgr import AgentSdkResponseMgr
from linksoul_agentsdk.mgr.task_flow_mgr import AgentSdkTaskFlowMgr
from linksoul_agentsdk.passive.asr2_llm import Asr2LlmResponse

from .conftest import FakeLinkskyClient


_SECRET = "0123456789abcdef0123456789abcdef"


def test_callback_type_mgr_offer_remove():
    from linksoul_agentsdk.enums import AgentCallbackType
    AgentSdkCallbackTypeMgr.offer("app1", AgentCallbackType.ASR_2_LLM)
    AgentSdkCallbackTypeMgr.offer("app1", AgentCallbackType.AUDIO_2_TTS)
    assert AgentSdkCallbackTypeMgr.get("app1") == frozenset({
        AgentCallbackType.ASR_2_LLM, AgentCallbackType.AUDIO_2_TTS,
    })
    AgentSdkCallbackTypeMgr.remove("app1")
    assert AgentSdkCallbackTypeMgr.get("app1") == frozenset()


def test_response_mgr_cleanup_ttl():
    sdk = AgentSdk.create("wss://x/v1", "app1", "test-app-key", _SECRET)
    client = FakeLinkskyClient(sdk)
    r = Asr2LlmResponse(client, "A", "C")
    AgentSdkResponseMgr.offer("ev_1", r)
    assert AgentSdkResponseMgr.get("ev_1") is r

    # 把 ttl 设小，跳过实际等待
    AgentSdkResponseMgr.set_ttl_ms_for_test(1)
    time.sleep(0.01)
    removed = AgentSdkResponseMgr.cleanup_once()
    AgentSdkResponseMgr.reset_ttl_for_test()
    assert removed == 1
    assert AgentSdkResponseMgr.get("ev_1") is None


def test_task_flow_mgr_register_and_unregister():
    sdk = AgentSdk.create("wss://x/v1", "app1", "test-app-key", _SECRET)
    flow = TaskFlowRequest(sdk, "AGENT_1", "flow_1")
    AgentSdkTaskFlowMgr.offer_request("flow_1", flow)
    assert AgentSdkTaskFlowMgr.get_request("flow_1") is flow
    AgentSdkTaskFlowMgr.remove_request("flow_1")
    assert AgentSdkTaskFlowMgr.get_request("flow_1") is None
