import asyncio
import logging
from typing import Dict

logger = logging.getLogger('app')

# 全局取消注册表: session_id -> asyncio.Event
_cancel_registry: Dict[str, asyncio.Event] = {}


def register_cancel_event(session_id: str) -> asyncio.Event:
    """注册一个取消事件"""
    event = asyncio.Event()
    _cancel_registry[session_id] = event
    logger.debug(f"Cancel event registered for session_id={session_id}")
    return event


def trigger_cancel(session_id: str) -> bool:
    """触发取消事件"""
    event = _cancel_registry.get(session_id)
    if event:
        event.set()
        logger.info(f"Cancel triggered for session_id={session_id}")
        return True
    logger.warning(f"No active session found for session_id={session_id}")
    return False


def unregister_cancel_event(session_id: str) -> None:
    """清理取消事件"""
    _cancel_registry.pop(session_id, None)
    logger.debug(f"Cancel event unregistered for session_id={session_id}")
