"""Small Ollama text-chat client; documentation example, not a production backend.

Preconditions: runtime already running; caller independently verified that the
selected installed model performs local inference. Inventory alone cannot prove
that. No model download, authentication gateway, queue or tool execution here.

When the reader runs this file it DOES call their local runtime. Author checks
used only AST parsing and in-memory protocol fixtures, never live inference.
Sample limits below are choices, not vendor defaults or an end-to-end deadline.
"""
import argparse
import json
import sys
import urllib.error
import urllib.request

BASE = "http://127.0.0.1:11434"
IO_TIMEOUT_SECONDS = 30  # per blocking operation, not whole-request deadline
MAX_RESPONSE_BYTES = 1024 * 1024
MAX_LINE_BYTES = 64 * 1024


class ClientError(Exception):
    pass


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


# Ignore environment proxies and refuse automatic HTTP redirects for this demo.
OPENER = urllib.request.build_opener(
    urllib.request.ProxyHandler({}), NoRedirect()
)


def decode_object(raw):
    try:
        value = json.loads(raw.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        raise ClientError("Invalid UTF-8 JSON from runtime") from exc
    if not isinstance(value, dict):
        raise ClientError("Expected a JSON object")
    if "error" in value:
        raise ClientError("Runtime returned an error; inspect redacted logs")
    return value


def read_object(response):
    raw = response.read(MAX_RESPONSE_BYTES + 1)
    if len(raw) > MAX_RESPONSE_BYTES:
        raise ClientError("Response exceeds this example's byte limit")
    return decode_object(raw)


def stream_content(response):
    """Yield text deltas. Early EOF/error is failure, even after partial text."""
    total = 0
    while True:
        raw = response.readline(MAX_LINE_BYTES + 1)
        if not raw:
            raise ClientError("Incomplete stream: no terminal done:true")
        total += len(raw)
        if len(raw) > MAX_LINE_BYTES or total > MAX_RESPONSE_BYTES:
            raise ClientError("Stream exceeds this example's byte limit")
        if not raw.strip():
            continue
        item = decode_object(raw)
        message = item.get("message", {})
        if not isinstance(message, dict):
            raise ClientError("Invalid message shape")
        content = message.get("content", "")
        if not isinstance(content, str):
            raise ClientError("Invalid text delta")
        if content:
            yield content
        if item.get("done") is True:
            return


def open_request(path, payload=None):
    data = None if payload is None else json.dumps(payload).encode("utf-8")
    request = urllib.request.Request(
        BASE + path, data=data,
        headers={"Content-Type": "application/json"},
        method="GET" if payload is None else "POST",
    )
    return OPENER.open(request, timeout=IO_TIMEOUT_SECONDS)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--model", required=True, help="Exact installed, verified local model name")
    parser.add_argument("--stream", action="store_true")
    args = parser.parse_args()
    with open_request("/api/tags") as response:
        inventory = read_object(response)
    entries = inventory.get("models", [])
    if not isinstance(entries, list):
        raise ClientError("Invalid model inventory")
    names = {item.get("name") for item in entries if isinstance(item, dict)}
    if args.model not in names:
        raise ClientError("Model name absent from inventory; select an installed local model")
    payload = {
        "model": args.model,
        "messages": [{"role": "user", "content": "Say hello in one sentence."}],
        "stream": args.stream,
        "options": {"num_predict": 256},  # chosen output budget, not a quality guarantee
    }
    with open_request("/api/chat", payload) as response:
        if args.stream:
            for delta in stream_content(response):
                print(delta, end="", flush=True)
            print()
        else:
            item = read_object(response)
            message = item.get("message", {})
            if item.get("done") is not True or not isinstance(message, dict):
                raise ClientError("Incomplete response or invalid message")
            content = message.get("content")
            if not isinstance(content, str):
                raise ClientError("Missing text content")
            print(content)


if __name__ == "__main__":
    try:
        main()
    except (ClientError, urllib.error.URLError, OSError, ValueError, TypeError):
        print("Request failed or incomplete. Partial text is not a completed answer. "
              "Inspect configuration and redacted runtime logs; do not retry blindly.",
              file=sys.stderr)
        sys.exit(1)
