import requests
import os
import json

class UniverseClient:
    def __init__(self, config_path: str = None, gateway_url: str = None):
        self.gateway_url = gateway_url or os.getenv("UNIVERSE_GATEWAY_URL", "http://localhost:8080")
        self.config_path = config_path or os.getenv("UNIVERSE_CONFIG")
        # In a real implementation, we might parse the config here to know about providers.
        # For now, we assume the Gateway handles everything.

    def chat_completion(self, model: str, messages: list, **kwargs):
        """
        Proxies a chat completion request to the UniverseOS Gateway.
        """
        payload = {
            "model": model,
            "messages": messages,
            **kwargs
        }
        
        # We send the request to the Gateway.
        # The Gateway expects a standardized format or transparent proxying.
        # For this v1, we'll assume the Gateway accepts a JSON body and forwards it.
        # We might need to specify the target provider/universe in headers or body.
        
        # Construct the URL. The Gateway might expose /v1/chat/completions to mimic OpenAI.
        url = f"{self.gateway_url}/v1/chat/completions"
        
        try:
            response = requests.post(url, json=payload)
            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            # Fallback or error handling
            print(f"UniverseOS Error: {e}")
            raise

_client = None

def init_universe(config_path: str = None, gateway_url: str = "http://localhost:8080"):
    global _client
    _client = UniverseClient(config_path=config_path, gateway_url=gateway_url)

def get_client():
    global _client
    if _client is None:
        _client = UniverseClient()
    return _client

