import asyncio
import logging
from connexity.CONST import CONNEXITY_URL
from uuid import UUID
import aiohttp

logger = logging.getLogger(__name__)


def convert_uuids(obj):
    if isinstance(obj, UUID):
        return str(obj)
    elif isinstance(obj, dict):
        return {k: convert_uuids(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [convert_uuids(item) for item in obj]
    return obj


async def send_data(answer_dict, api_key, url=CONNEXITY_URL):
    try:
        print('CONNEXITY SDK DEBUG| CALL COLLECTED DATA:', flush=True)
        print(answer_dict, flush=True)
        answer_dict = convert_uuids(answer_dict)
        
        timeout = aiohttp.ClientTimeout(total=10)
        
        async with aiohttp.ClientSession(timeout=timeout) as session:
            async with session.post(url, headers={"X-API-KEY": api_key}, json=answer_dict) as response:
                if response.status != 200:
                    logger.warning(f"Connexity SDK: Failed to send data (status {response.status})")
                else:
                    logger.debug(f"Connexity SDK: Data sent successfully (status {response.status})")
    
    except asyncio.TimeoutError:
        logger.warning("Connexity SDK: Timeout while sending data to API")
    
    except aiohttp.ClientError as e:
        logger.warning(f"Connexity SDK: Network error while sending data: {e}")
    
    except Exception as e:
        logger.error(f"Connexity SDK: Unexpected error while sending data: {e}", exc_info=True)
