"""
Worker process for {{ agent_name }} agent.

Connects to message bus, listens for tasks, and executes them.
"""

import asyncio
import logging
from evenage.core.agent import Agent
from evenage.core.config import AgentConfig, load_runtime_config
from agents.{{ agent_name }}.handler import {{ agent_name.capitalize() }}Agent

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s"
)
logger = logging.getLogger(__name__)


async def main():
    """Run agent worker."""
    # Load runtime configuration (.evenage/config.json overrides env)
    # You can customize backends by setting environment variables:
    #   QUEUE_BACKEND=redis|memory
    #   DB_BACKEND=postgres|sqlite
    #   LLM_BACKEND=openai|anthropic|gemini|noop
    #   CACHE_BACKEND=redis|inmemory
    # Or programmatically:
    env_config = load_runtime_config()
    
    agent_config = AgentConfig(
        name="{{ agent_name }}",
        # Source role/goal from the handler class to avoid drift with @actor metadata
        role={{ agent_name.capitalize() }}Agent.ROLE,
        goal={{ agent_name.capitalize() }}Agent.GOAL,
    )
    
    # Create agent
    agent = {{ agent_name.capitalize() }}Agent(agent_config, env_config)
    
    # Connect to message bus and register
    await agent.connect_bus()
    logger.info(f"Agent {agent_config.name} registered and listening for tasks")
    
    try:
        # Consume tasks continuously
        while True:
            tasks = await agent.bus.consume_tasks(agent_config.name, block_ms=5000, count=1)
            for task in tasks:
                logger.info(f"Received task: {task.get('task_id')}")
                
                # Handle task
                result = await agent.handle(task.get('payload', {}))
                
                # Publish response
                await agent.bus.publish_response(task['task_id'], result)
                logger.info(f"Task {task['task_id']} completed")
    
    except KeyboardInterrupt:
        logger.info("Shutting down...")
    finally:
        await agent.shutdown()
        logger.info("Agent shut down")


if __name__ == "__main__":
    asyncio.run(main())
