"""Auto-looping tool execution with akashic.run().

run() handles the execute-append-resend loop automatically
until the model stops making tool calls.
"""
from akashic import Akashic
from openai import OpenAI

client = OpenAI()

JOHNATHAN_API_KEY = "ak_9MZGg1FA14K2QKxYRzm4rYR7HcZNNjIlKMf3rYdYvv4"

def on_auth(urls):
    for url in urls:
        print(f"Sign into {url['serverLabel']}: {url['authorizationUrl']}")

john = Akashic(api_key=JOHNATHAN_API_KEY, on_auth=on_auth)

messages = []

def log_tools(john):
    print(f"\n--- {len(john.tools)} tools selected ---")
    for t in john.tools:
        print(f"  {t['name']}")
    if not john.tools:
        print("No tools needed for this request.\n")

while True:

    data = input("User: ")
    messages.append({"role": "user", "content": data})

    john.register(data)

    log_tools(john)

    response = client.responses.create(
            model="gpt-4.1-nano",
            input=messages,
            tools=john.tools
            )

    # Auto-loop: run() keeps executing tools until the model is done
    response = john.run(
        response,
        create=lambda msgs: client.responses.create(
            model="gpt-4.1-nano", input=msgs, tools=john.tools
        ),
    )

    # Grab the final text output
    messages.append({"role": "assistant", "content": response.output_text})
    print(f"Assistant: {response.output_text}\n")
