"""
===============================================================================
ANTIGRAVITY SOVEREIGN AGENT CLIENT SDK (Python 3.8+)
Machine-to-Machine (M2M) AI Agent Gateway for the 14-SaaS Conglomerate
Sole Exclusive Owner: Kamel HOMRI (CEO Master & Founder)
© 2026 Kamel Homri. All Rights Reserved.
===============================================================================
"""

import json
import urllib.request
import urllib.error

DEFAULT_GATEWAY = "https://globconnectworld.com"

class AntigravityAgentClient:
    def __init__(self, license_key: str, gateway_url: str = DEFAULT_GATEWAY):
        self.license_key = license_key.strip().toUpperCase() if hasattr(license_key, 'toUpperCase') else license_key.strip().upper()
        self.gateway_url = gateway_url.rstrip('/')
        self.session = None
        self._authenticate()

    def _authenticate(self):
        url = f"{self.gateway_url}/api/v1/sso/verify"
        payload = json.dumps({"licenseKey": self.license_key}).encode('utf-8')
        req = urllib.request.Request(url, data=payload, headers={'Content-Type': 'application/json'}, method='POST')
        try:
            with urllib.request.urlopen(req, timeout=10) as resp:
                data = json.loads(resp.read().decode('utf-8'))
                if data.get("valid"):
                    self.session = data
                    print(f"👑 [ANTIGRAVITY-SDK] Authentifié avec succès. Accès débloqué aux 14 SaaS souverains ({data.get('email')}).")
                else:
                    raise PermissionError(f"Licence invalide: {data.get('error')}")
        except urllib.error.HTTPError as e:
            err_body = e.read().decode('utf-8')
            raise PermissionError(f"Erreur d'authentification ({e.code}): {err_body}")

    def get_catalog(self):
        """Récupère le catalogue machine-readable des 14 plateformes"""
        url = f"{self.gateway_url}/api/v1/agent-gateway/catalog"
        req = urllib.request.Request(url, headers={'Authorization': f"Bearer {self.license_key}"})
        with urllib.request.urlopen(req, timeout=10) as resp:
            return json.loads(resp.read().decode('utf-8'))

    def ping_health(self):
        url = f"{self.gateway_url}/api/v1/health"
        with urllib.request.urlopen(url, timeout=5) as resp:
            return json.loads(resp.read().decode('utf-8'))

    def dispatch_agent_task(self, target_saas: str, action: str, parameters: dict):
        """Exécute une tâche d'agent autonome sur l'un des 14 SaaS"""
        if not self.session:
            raise PermissionError("Client non authentifié.")
        
        valid_platforms = self.session.get("accessiblePlatforms", [])
        if target_saas not in valid_platforms:
            raise ValueError(f"SaaS '{target_saas}' inconnu ou non accessible. Plateformes autorisées: {valid_platforms}")

        payload = {
            "licenseKey": self.license_key,
            "targetSaaS": target_saas,
            "action": action,
            "parameters": parameters
        }
        url = f"{self.gateway_url}/api/v1/agent-gateway/execute"
        req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'), headers={'Content-Type': 'application/json'}, method='POST')
        with urllib.request.urlopen(req, timeout=15) as resp:
            return json.loads(resp.read().decode('utf-8'))
