#!/usr/bin/env python3
"""Direct test of nanobot agent - write to file"""
import asyncio
import sys
sys.path.insert(0, '.')

log_file = open('/tmp/nanobot_debug.log', 'w')

def log(msg):
    log_file.write(f"{msg}\n")
    log_file.flush()
    print(msg, file=sys.stderr)
    sys.stderr.flush()

try:
    log("Starting test...")
    
    log("Loading config...")
    from nanobot.config.loader import load_config
    config = load_config()
    log(f"Config loaded. Provider type: {type(config.providers)}")
    
    log("Creating bus and provider...")
    from nanobot.bus.queue import MessageBus
    bus = MessageBus()
    from nanobot.cli.commands import _make_provider
    provider = _make_provider(config)
    log(f"Provider created: {type(provider)}")
    
    log("Creating agent loop...")
    from nanobot.agent.loop import AgentLoop
    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,
    )
    log("Agent loop created")
    
    log("Processing message...")
    async def run():
        response = await agent_loop.process_direct("Hello, what is 2+5?", "cli:test")
        log(f"Response received: {response}")
        log(f"Response type: {type(response)}")
        if response:
            log(f"Response content: {response.content}")
            return response.content or "(empty)"
        else:
            log("No response")
            return "(no response)"
    
    result = asyncio.run(run())
    log(f"Final result: {result}")
    print(f"\n=== RESULT ===")
    print(result)
    
except Exception as e:
    import traceback
    error_msg = f"ERROR: {e}\n{traceback.format_exc()}"
    log(error_msg)
    print(error_msg, file=sys.stderr)
finally:
    log_file.close()

