#!/usr/bin/env python3
"""Debug script to test nanobot AirLLM setup"""
import sys
import asyncio
import traceback

# Ensure output is not buffered
sys.stdout.reconfigure(line_buffering=True)
sys.stderr.reconfigure(line_buffering=True)

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

log("=" * 60)
log("NANOBOT AIRLLM DEBUG SCRIPT")
log("=" * 60)

try:
    log("\n[1/6] Adding current directory to path...")
    import os
    sys.path.insert(0, os.getcwd())
    
    log("[2/6] Importing nanobot modules...")
    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
    
    log("[3/6] Loading configuration...")
    config = load_config()
    log(f"     Provider name: {config.get_provider_name()}")
    log(f"     Default model: {config.agents.defaults.model}")
    
    log("[4/6] Creating provider...")
    provider = _make_provider(config)
    log(f"     Provider type: {type(provider).__name__}")
    log(f"     Default model: {provider.get_default_model()}")
    
    log("[5/6] Creating agent loop...")
    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,
    )
    log("     Agent loop created successfully")
    
    log("[6/6] Processing test message...")
    log("     Message: 'Hello, what is 2+5?'")
    
    async def process():
        try:
            response = await agent_loop.process_direct("Hello, what is 2+5?", "cli:debug")
            log(f"\n{'='*60}")
            log("RESPONSE RECEIVED")
            log(f"{'='*60}")
            log(f"Response object: {response}")
            log(f"Response type: {type(response)}")
            if response:
                log(f"Response content: {repr(response.content)}")
                log(f"Content length: {len(response.content) if response.content else 0}")
                log(f"\n{'='*60}")
                log("FINAL OUTPUT:")
                log(f"{'='*60}")
                print(response.content or "(empty response)")
            else:
                log("ERROR: Response is None!")
                return 1
        except Exception as e:
            log(f"\n{'='*60}")
            log("ERROR DURING PROCESSING")
            log(f"{'='*60}")
            log(f"Exception: {e}")
            log(f"Type: {type(e).__name__}")
            traceback.print_exc()
            return 1
        return 0
    
    exit_code = asyncio.run(process())
    sys.exit(exit_code)
    
except ImportError as e:
    log(f"\n{'='*60}")
    log("IMPORT ERROR")
    log(f"{'='*60}")
    log(f"Failed to import: {e}")
    traceback.print_exc()
    sys.exit(1)
except Exception as e:
    log(f"\n{'='*60}")
    log("UNEXPECTED ERROR")
    log(f"{'='*60}")
    log(f"Exception: {e}")
    log(f"Type: {type(e).__name__}")
    traceback.print_exc()
    sys.exit(1)

