"""
Typing indicator utilities for bot interactions.
"""
import asyncio
import contextlib
from typing import Optional

from aiogram import Bot
from aiogram.enums import ChatAction


async def typing_loop(
    bot: Bot, 
    chat_id: int, 
    stop_event: asyncio.Event, 
    action: ChatAction = ChatAction.TYPING
) -> None:
    """
    Show typing indicator in a loop until stop event is set.
    
    Args:
        bot: Bot instance
        chat_id: Chat ID to show typing in
        stop_event: Event to stop the loop
        action: Chat action to show (default: TYPING)
    """
    try:
        while not stop_event.is_set():
            await bot.send_chat_action(chat_id, action)
            await asyncio.sleep(4)
    except Exception:
        pass


async def show_typing_with_context(
    bot: Bot, 
    chat_id: int, 
    duration: Optional[float] = None
) -> None:
    """
    Show typing indicator for a specific duration or until manually stopped.
    
    Args:
        bot: Bot instance
        chat_id: Chat ID to show typing in
        duration: Duration in seconds (None for manual control)
    """
    stop_event = asyncio.Event()
    typing_task = asyncio.create_task(typing_loop(bot, chat_id, stop_event))
    
    try:
        if duration:
            await asyncio.sleep(duration)
        else:
            # Return control to caller - they need to call stop_event.set()
            return stop_event, typing_task
    finally:
        if duration:
            stop_event.set()
            with contextlib.suppress(Exception):
                await typing_task
