import aiohttp
import logging
from typing import Optional, Dict, Any
from shared.config import settings

logger = logging.getLogger("shared.http_client")

class HTTPClient:
    """HTTP client for inter-service communication"""
    
    def __init__(self):
        self.session: Optional[aiohttp.ClientSession] = None
    
    async def connect(self):
        """Create aiohttp session"""
        if not self.session:
            timeout = aiohttp.ClientTimeout(total=10)
            self.session = aiohttp.ClientSession(timeout=timeout)
    
    async def disconnect(self):
        """Close aiohttp session"""
        if self.session:
            await self.session.close()
            self.session = None
    
    async def get(self, url: str, headers: Optional[Dict[str, str]] = None) -> aiohttp.ClientResponse:
        """Make GET request"""
        await self.connect()
        try:
            return await self.session.get(url, headers=headers)
        except Exception as e:
            logger.error(f"GET request failed to {url}: {e}")
            raise
    
    async def post(self, url: str, data: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None) -> aiohttp.ClientResponse:
        """Make POST request"""
        await self.connect()
        try:
            return await self.session.post(url, json=data, headers=headers)
        except Exception as e:
            logger.error(f"POST request failed to {url}: {e}")
            raise

# Global HTTP client instance
http_client = HTTPClient()
