"""Kleiner lokaler Funktionstest; kein Qualitätsbenchmark.
Benötigt Python3 und einen bereits gestarteten Kolibri-Endpunkt.
Es werden keine Pakete installiert und keine Modellgewichte geladen.
"""
import json
import os
import sys
import urllib.error
import urllib.request

BASE = "http://127.0.0.1:8000/v1"
MODEL = "Aleph-Alpha/Kolibri-1"

def api(path, payload=None):
    headers = {"Content-Type": "application/json"}
    key = os.environ.get("KOLIBRI_API_KEY")
    if key:
        headers["Authorization"] = "Bearer " + key
    data = None if payload is None else json.dumps(payload).encode("utf-8")
    request = urllib.request.Request(BASE + path, data=data, headers=headers)
    with urllib.request.urlopen(request, timeout=180) as response:
        return json.load(response)

def main():
    available = api("/models")
    ids = {m.get("id") for m in available.get("data", [])}
    if MODEL not in ids:
        raise ValueError("Modell-ID nicht in /v1/models gefunden. Konfiguration prüfen.")
    result = api("/chat/completions", {
        "model": MODEL,
        "messages": [{"role": "user", "content":
            "Quelle A: Der Termin ist um 9 Uhr. Nenne nur die Uhrzeit aus Quelle A."}],
        "max_tokens": 128,
        "chat_template_kwargs": {"enable_thinking": False},
    })
    choices = result.get("choices") or []
    if not choices:
        raise ValueError("Antwort enthält keine choices. Vollständige API-Antwort prüfen.")
    first = choices[0]
    answer = (first.get("message") or {}).get("content")
    if not isinstance(answer, str) or not answer.strip():
        raise ValueError("Kein Text in choices[0].message.content. Reasoning und Output prüfen.")
    print("Antwort:", answer)
    if first.get("finish_reason") == "length":
        raise ValueError("Ausgabe wurde am Tokenlimit abgeschnitten.")
    allowed = {"9 uhr", "9:00", "09:00", "9:00 uhr", "09:00 uhr"}
    if answer.strip().rstrip(".").casefold() not in allowed:
        raise ValueError("Uhrzeit weicht vom kleinen Sollfall ab. Antwort selbst prüfen.")
    print("Kleiner Sollfall erfüllt. Keine Aussage über allgemeine Qualität oder Sicherheit.")

if __name__ == "__main__":
    try:
        main()
    except (urllib.error.URLError, ValueError, KeyError, TypeError, json.JSONDecodeError) as error:
        print("Prüfung fehlgeschlagen:", error, file=sys.stderr)
        raise SystemExit(1)
