import aiohttp
from typing import Optional


class IPGeolocationService:
    def __init__(self):
        self.api_url = "http://ip-api.com/json/"
        self._session = None

    async def get_session(self) -> aiohttp.ClientSession:
        if self._session is None or self._session.closed:
            self._session = aiohttp.ClientSession()
        return self._session

    async def get_country(self, ip_address: str) -> Optional[str]:
        try:
            session = await self.get_session()
            async with session.get(f"{self.api_url}{ip_address}") as response:
                data = await response.json()
                if data.get("status") == "success":
                    return data.get("country")
                return None
        except Exception as e:
            print(f"Error determining country for IP {ip_address}: {e}")
            return None
    async def get_current_country(self) -> Optional[str]:
        try:
            session = await self.get_session()
            async with session.get(f"{self.api_url}") as response:
                data = await response.json()
                if data.get("status") == "success":
                    return data.get("country")
                return None
        except Exception as e:
            print(f"Error determining current country: {e}")
            return None


    async def close(self):
        if self._session and not self._session.closed:
            await self._session.close()

# Пример использования:
"""
geo_service = IPGeolocationService()
# В асинхронной функции:
country = await geo_service.get_country("8.8.8.8")  # Вернёт 'US' для Google DNS
await geo_service.close()  # Не забудьте закрыть сессию когда она больше не нужна
"""
