import asyncio
import logging
from typing import Dict

logger = logging.getLogger('app')

# Global cancel registry: session_id -> asyncio.Event
_cancel_registry: Dict[str, asyncio.Event] = {}


def register_cancel_event(session_id: str) -> asyncio.Event:
    """Register a cancel 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:
    """Trigger a cancel event."""
    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:
    """Clean up a cancel event."""
    _cancel_registry.pop(session_id, None)
    logger.debug(f"Cancel event unregistered for session_id={session_id}")
