#!/usr/bin/env python3
"""Direct test of AirLLM provider"""
import asyncio
import sys
import traceback

# Force output
sys.stdout.reconfigure(line_buffering=True)
sys.stderr.reconfigure(line_buffering=True)

print("=== STARTING TEST ===", flush=True)

try:
    print("1. Importing...", flush=True)
    from nanobot.config.loader import load_config
    from nanobot.bus.queue import MessageBus
    from nanobot.agent.loop import AgentLoop
    from nanobot.cli.commands import _make_provider
    
    print("2. Loading config...", flush=True)
    config = load_config()
    print(f"   Config loaded. Provider name: {config.get_provider_name()}", flush=True)
    
    print("3. Creating provider...", flush=True)
    provider = _make_provider(config)
    print(f"   Provider created: {type(provider)}", flush=True)
    
    print("4. Creating agent loop...", flush=True)
    bus = MessageBus()
    agent_loop = AgentLoop(
        bus=bus,
        provider=provider,
        workspace=config.workspace_path,
        brave_api_key=config.tools.web.search.api_key or None,
        exec_config=config.tools.exec,
        restrict_to_workspace=config.tools.restrict_to_workspace,
    )
    print("   Agent loop created", flush=True)
    
    print("5. Processing message...", flush=True)
    
    async def test():
        response = await agent_loop.process_direct("Hello, what is 2+5?", "cli:test")
        print(f"6. Response: {response}", flush=True)
        print(f"   Response type: {type(response)}", flush=True)
        if response:
            print(f"   Response content: {response.content}", flush=True)
            print(f"\n=== FINAL RESPONSE ===", flush=True)
            print(response.content or "(empty)", flush=True)
        else:
            print("   NO RESPONSE", flush=True)
    
    asyncio.run(test())
    
except Exception as e:
    print(f"\n=== ERROR ===", flush=True)
    print(f"{e}", flush=True)
    traceback.print_exc(file=sys.stderr)
    sys.exit(1)

print("\n=== TEST COMPLETE ===", flush=True)

