# examples/basic.py
"""
Basic end-to-end example for openai-resptools.

This script demonstrates the standard OpenAI tool-calling flow:
1) Send a prompt + tool definitions
2) Model returns one or more `function_call` items with JSON arguments
3) Your app executes tools and returns `function_call_output` items with matching `call_id`
4) Send the updated input back until the model returns final text [page:9]
"""

import os
from typing import Dict

from openai import OpenAI

from openai_resptools import ToolRegistry, ToolRunner


def main() -> None:
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        raise RuntimeError("Please set OPENAI_API_KEY environment variable")

    # In-memory storage for the demo.
    store: Dict[str, str] = {}

    registry = ToolRegistry()

    @registry.tool()
    def write(key: str, text: str) -> dict:
        """Save text under a key and return a small status payload."""
        store[key] = text
        return {"ok": True, "key": key, "length": len(text)}

    @registry.tool()
    def read(key: str) -> dict:
        """Read text by key. Returns null text if missing."""
        return {"key": key, "text": store.get(key)}

    client = OpenAI(api_key=api_key)

    # Use any tool-capable model you have access to.
    model = os.getenv("OPENAI_MODEL", "gpt-4o-mini")

    runner = ToolRunner(
        client,
        model=model,
        registry=registry,
        max_iters=6,
        parallel_tool_calls=False,
    )

    prompt = (
        "Do the following steps using tools:\n"
        "1) Call write to save the text 'Hello from tools!' under key 'greeting'.\n"
        "2) Call read for key 'greeting'.\n"
        "3) Reply with ONLY the value of the text you read.\n"
    )

    result = runner.run(prompt)

    print("Model output:")
    print(result.text)


if __name__ == "__main__":
    main()
