import httpx
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class OBVersionManager:
    def __init__(self):
        self.raw_data = None
        self.ob_version = None
        self.server_url = None
        self.gop_urls = []
        self.is_loaded = False

    async def fetch(self):
        """
        Fetches live configuration from the version server.
        Returns True if successful, False otherwise.
        """
        url = "https://bdversion.ggbluefox.com/live/ver.php"
        
        params = {
            "version": "1.120.1",
            "lang": "ar",
            "device": "android",
            "channel": "android",
            "appstore": "googleplay",
            "region": "ME",
            "whitelist_version": "1.3.0",
            "whitelist_sp_version": "1.0.0",
            "device_name": "google G011A",
            "device_CPU": "ARMv7 VFPv3 NEON VMH",
            "device_GPU": "Adreno (TM) 640",
            "device_mem": "1993"
        }

        headers = {
            "User-Agent": "Dalvik/2.1.0 (Linux; U; Android 10; SM-G965F Build/QP1A.190711.020)",
            "Accept-Encoding": "gzip",
            "Connection": "Keep-Alive"
        }

        try:
            async with httpx.AsyncClient(timeout=15, verify=False) as client:
                logger.info("Fetching OB Version info...")
                response = await client.get(url, params=params, headers=headers)
            
            response.raise_for_status()
            data = response.json()

            if data.get("code") != 0:
                logger.error(f"Server returned error code: {data.get('code')}")
                return False

            self.raw_data = data
            
            self.ob_version = data.get("latest_release_version")
            self.server_url = data.get("server_url")
            
            raw_gop = data.get("gop_url", "")
            if raw_gop:
                self.gop_urls = raw_gop.split(";")
            
            if not self.ob_version or not self.server_url:
                logger.error("Failed to parse critical data (version or server_url is missing)")
                return False

            self.is_loaded = True
            
            logger.info(f"OB VERSION LOADED: {self.ob_version}")
            logger.info(f"LOGIN SERVER: {self.server_url}")
            
            return True

        except Exception as e:
            logger.error(f"OB Fetch Failed: {e}")
            return False

    def get_ob(self):
        return self.ob_version

    def get_login_server(self):
        return self.server_url

    def get_gop_server(self):
        if self.gop_urls:
            return self.gop_urls[0]
        return None

    def get_raw_data(self):
        return self.raw_data