"""Thin client for the EXL AI Gateway.

Per the gateway's own developer playbook: it's an OpenAI-compatible LiteLLM proxy. Auth,
routing, PII guardrails, caching and observability all live in the gateway itself — this file
is deliberately just a client, not a reimplementation of any of that.

Config is three values from the environment (see .env): GATEWAY_URL, VIRTUAL_KEY, MODEL_ID.
"""
import os

from openai import OpenAI


def load_env(path=None):
    """Minimal .env loader so this runs without an extra dependency for one file."""
    path = path or os.path.join(os.path.dirname(__file__), ".env")
    if not os.path.exists(path):
        return
    for line in open(path):
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, _, value = line.partition("=")
        os.environ.setdefault(key.strip(), value.strip())


load_env()

GATEWAY_URL = os.environ.get("GATEWAY_URL")
VIRTUAL_KEY = os.environ.get("VIRTUAL_KEY")
MODEL_ID = os.environ.get("MODEL_ID")


class GatewayClient:
    """Wraps the OpenAI SDK pointed at the gateway. One call in, one message out."""

    def __init__(self, base_url=GATEWAY_URL, api_key=VIRTUAL_KEY, model=MODEL_ID):
        if not (base_url and api_key and model):
            raise RuntimeError(
                "GATEWAY_URL, VIRTUAL_KEY and MODEL_ID must all be set (see .env)")
        self.model = model
        self._client = OpenAI(base_url=base_url, api_key=api_key)

    def complete(self, messages, tools=None, tool_choice=None, **kwargs):
        """One chat-completions call. Returns the raw message object (may carry tool_calls)."""
        kwargs = dict(kwargs)
        if tools:
            kwargs["tools"] = tools
            if tool_choice:
                kwargs["tool_choice"] = tool_choice
        response = self._client.chat.completions.create(
            model=self.model, messages=messages, **kwargs)
        return response.choices[0].message
