# Python 3: server-side example. No third-party dependencies.
import http.client
import json
import os
from urllib.parse import urlsplit

origin = urlsplit(os.environ["IRANNET_AI_ORIGIN"])
key = os.environ["IRANNET_API_KEY"]
model = os.environ["IRANNET_MODEL_ID"]
if (origin.scheme != "https" or not origin.hostname or origin.username
        or origin.password or origin.path not in ("", "/")
        or origin.query or origin.fragment):
    raise ValueError("Use the official HTTPS origin without /v1")
if not key or not model or any(c in key for c in "\r\n"):
    raise ValueError("Invalid account configuration")

def call(path, payload=None):
    body = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
    connection = http.client.HTTPSConnection(origin.hostname, origin.port or 443, timeout=60)
    try:
        connection.request("POST" if body is not None else "GET", path, body=body,
            headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
        response = connection.getresponse()
        if not 200 <= response.status < 300:
            raise RuntimeError("API returned HTTP " + str(response.status))
        kind = response.getheader("Content-Type", "").split(";", 1)[0].strip().lower()
        if kind != "application/json":
            raise RuntimeError("Unexpected response type")
        raw = response.read(2_000_001)
        if len(raw) > 2_000_000:
            raise RuntimeError("Response exceeds application limit")
        try:
            return json.loads(raw)
        except (ValueError, UnicodeDecodeError):
            raise RuntimeError("Invalid JSON response") from None
    finally:
        connection.close()

# First inspect the permitted models; keep this output private.
models = call("/v1/models")
result = call("/v1/chat/completions", {
    "model": model,
    "messages": [{"role": "user", "content": "یک سلام کوتاه فارسی بنویس."}]
})
print(json.dumps(result, ensure_ascii=False))
