"""Single-pass tool execution with akashic.execute().

The user controls the loop — execute() runs Akashic tools once
and returns function_call_output dicts to append to the conversation.
"""
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
            )

    # Loop: execute tool calls, feed results back manually
    while True:
        tool_outputs = john.execute(response.output)

        if not tool_outputs:
            break  # model is done calling tools

        messages += response.output
        messages += tool_outputs

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

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