import asyncio
from serverside.consts import logger, executor, running_tasks

async def run_in_thread(name, func, *args, **kwargs):
    loop = asyncio.get_event_loop()
    try:
        await loop.run_in_executor(executor, func, *args, **kwargs)
    except asyncio.CancelledError:
        logger.info(f"{name} task cancelled.")
        raise
    except Exception as e:
        logger.error(f"Error in {name}: {e}")

async def stop_task(name):
    task = running_tasks.get(name)
    if task:
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            logger.info(f"{name} task stopped.")
            running_tasks.pop(name, None)
        except Exception as e:
            logger.error(f"Error stopping {name} task: {e}")

async def stop_all():
    logger.info("Stopping all services...")
    for _, task in running_tasks.items():
        task.cancel()
    await asyncio.gather(*running_tasks.values(), return_exceptions=True)
    running_tasks.clear()
    logger.info("All services stopped.")
