import requests
from .utils import format_seconds, get_random_ua

class InfoClient:
    def __init__(self, timeout=30):
        self.base_url = "https://100067.connect.garena.com/game/account_security/bind:get_bind_info"
        self.timeout = timeout
        self.session = requests.Session()

    def get_bind_info(self, access_token):
        if not access_token:
            return {"status": "error", "message": "Access token is required"}

        params = {'app_id': "100067", 'access_token': access_token}
        headers = {
            'User-Agent': get_random_ua(),
            'Connection': "Keep-Alive",
            'Accept-Encoding': "gzip"
        }
        
        try:
            response = self.session.get(
                self.base_url, 
                params=params, 
                headers=headers, 
                timeout=self.timeout
            )
            

            response.raise_for_status()
            data = response.json()
            
            email = data.get("email", "")
            email_to_be = data.get("email_to_be", "")
            countdown = data.get("request_exec_countdown", 0)
            
            
            summary = "No recovery email set"
            if email == "" and email_to_be != "":
                summary = f"Pending confirmation: {email_to_be} - In: {format_seconds(countdown)}"
            elif email != "":
                summary = f"Email confirmed: {email}"

            return {
                "status": "success",
                "data": {
                    "current_email": email,
                    "pending_email": email_to_be,
                    "countdown_human": format_seconds(countdown),
                    "raw": data
                },
                "summary": summary
            }

        except requests.exceptions.RequestException as e:
            return {"status": "error", "message": f"Network error: {str(e)}"}
        except Exception as e:
            return {"status": "error", "message": f"Unexpected error: {str(e)}"}
