"""Orchestration AI : route les requêtes des clients vers LiteLLM (s01).

LiteLLM (:4000) est OpenAI-compatible et route lui-même vers Qwen3 (g01) ou Claude
selon l'alias `hermes-default` / `hermes-switch`. L'intégration des outils Hermes
(« agir sur Funk » via le gateway :8080) est une étape ultérieure.
"""

from __future__ import annotations

import httpx

from stt_server.config import settings


async def ask(
    text: str,
    model: str | None = None,
    history: list[dict] | None = None,
    memories: list[str] | None = None,
) -> str:
    system = settings.system_prompt
    if memories:
        souvenirs = "\n".join(f"- {m}" for m in memories)
        system += (
            "\n\nÉléments de mémoire long-terme (peuvent aider, ignore si hors-sujet) :\n"
            + souvenirs
        )
    messages = [{"role": "system", "content": system}]
    if history:
        messages += history
    messages.append({"role": "user", "content": text})
    payload = {
        "model": model or settings.model,
        "messages": messages,
        "max_tokens": settings.max_tokens,
        "temperature": settings.temperature,
    }
    headers = {"Authorization": f"Bearer {settings.litellm_key}"}
    async with httpx.AsyncClient(timeout=settings.request_timeout) as client:
        r = await client.post(settings.litellm_url, json=payload, headers=headers)
        r.raise_for_status()
        return r.json()["choices"][0]["message"]["content"].strip()
