

import asyncio
import functools
import requests

from .utils import isWindows
from .async_loop import runAsync # Import runAsync


def runAsyncRequest(url, method = requests.get, onResponse:callable = None):
    async def task():
        try:
            partial_method_call = functools.partial(method, url)
            current_loop = asyncio.get_event_loop()
            response = await current_loop.run_in_executor(None, partial_method_call)

            if onResponse:
                onResponse(response)
                
        except Exception as e:
            error_msg = str(e)
            if "Connection refused" in error_msg:
                print("Localserver connection refused - server may not be running")
            elif "Max retries exceeded" in error_msg:
                print("Localserver: Could not connect after multiple attempts")
            else:
                print(f"Localserver connection error: {e}")
            if onResponse:
                onResponse(None)

    runAsync(task())


def register():
    if isWindows():
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
